|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const fs = require('fs') |
| 4 | +const path = require('path') |
| 5 | +const url = require('url') |
| 6 | +const { chromium } = require('playwright') |
| 7 | + |
| 8 | +const htmlToPDF = async (htmlPath, options) => { |
| 9 | + if (!htmlPath.endsWith('.html')) { |
| 10 | + throw new Error(`Input file must have the '.html' extension: ${htmlPath}`) |
| 11 | + } |
| 12 | + if (!fs.existsSync(htmlPath)) { |
| 13 | + throw new Error(`Input file does not exist: ${htmlPath}`) |
| 14 | + } |
| 15 | + const outputPath = htmlPath.replace(/\.html$/, '.pdf') |
| 16 | + if (!options.force && fs.existsSync(outputPath)) { |
| 17 | + throw new Error(`Output file already exists: ${outputPath}`) |
| 18 | + } |
| 19 | + |
| 20 | + const browser = await chromium.launch({ channel: 'chrome' }) |
| 21 | + const page = await browser.newPage() |
| 22 | + |
| 23 | + const htmlPathURL = url.pathToFileURL(htmlPath).toString() |
| 24 | + |
| 25 | + console.log(`Processing ${htmlPathURL}...`) |
| 26 | + await page.goto(htmlPathURL, { waitUntil: 'load' }) |
| 27 | + |
| 28 | + await page.pdf({ |
| 29 | + path: outputPath, |
| 30 | + format: 'A4', |
| 31 | + margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' }, |
| 32 | + }) |
| 33 | + await browser.close() |
| 34 | +} |
| 35 | + |
| 36 | +const args = process.argv.slice(2) |
| 37 | +const options = {} |
| 38 | +while (args?.[0].startsWith('-')) { |
| 39 | + const arg = args.shift() |
| 40 | + if (arg === '--force' || arg === '-f') options.force = true |
| 41 | + else throw new Error(`Unknown argument: ${arg}`) |
| 42 | +} |
| 43 | + |
| 44 | +if (args.length !== 1) { |
| 45 | + process.stderr.write('Usage: html-to-pdf.js [--force] <input-file.html>\n') |
| 46 | + process.exit(1) |
| 47 | +} |
| 48 | + |
| 49 | +htmlToPDF(args[0], options).catch(e => { |
| 50 | + process.stderr.write(`${e.stack}\n`) |
| 51 | + process.exit(1) |
| 52 | +}) |
0 commit comments