Skip to content

Commit 71c911b

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 632c576 commit 71c911b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

script/html-to-pdf.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
landscape: true,
32+
margin: { top: '0cm', bottom: '0cm', left: '0cm', right: '0cm' },
33+
})
34+
await browser.close()
35+
}
36+
37+
const args = process.argv.slice(2)
38+
const options = {}
39+
while (args?.[0].startsWith('-')) {
40+
const arg = args.shift()
41+
if (arg === '--force' || arg === '-f') options.force = true
42+
else throw new Error(`Unknown argument: ${arg}`)
43+
}
44+
45+
if (args.length !== 1) {
46+
process.stderr.write('Usage: html-to-pdf.js [--force] <input-file.html>\n')
47+
process.exit(1)
48+
}
49+
50+
htmlToPDF(args[0], options).catch(e => {
51+
process.stderr.write(`${e.stack}\n`)
52+
process.exit(1)
53+
})

0 commit comments

Comments
 (0)