Skip to content

Commit 358a843

Browse files
committed
Add a script to convert HTML to PDF
This could be used, for example, to render a PDF version of the shiny new Git Cheat Sheet. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent eddeaf2 commit 358a843

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

script/html-to-pdf.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)