|
| 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 insertPDFLink = (htmlPath) => { |
| 9 | + const html = fs.readFileSync(htmlPath, 'utf-8') |
| 10 | + if (html.includes('class="pdf-link"')) { |
| 11 | + return |
| 12 | + } |
| 13 | + // get baseURL prefix via the `favicon.ico` link, it's in the top-level directory |
| 14 | + const match = html.match(/<link href="(.*?)favicon\.ico"/) |
| 15 | + if (!match) throw new Error('Failed to determine baseURL prefix from favicon.ico link') |
| 16 | + const img = `<img src="${match[1]}/images/pdf.png" />` |
| 17 | + const updatedHtml = html.replace( |
| 18 | + /<h1/, |
| 19 | + `<a class="pdf-link" href="${path.basename(htmlPath, '.html')}.pdf">${img}</a>$&` |
| 20 | + ) |
| 21 | + if (updatedHtml === html) throw new Error('Failed to insert PDF link, no <h1> found') |
| 22 | + fs.writeFileSync(htmlPath, updatedHtml, 'utf-8') |
| 23 | +} |
| 24 | + |
| 25 | +const htmlToPDF = async (htmlPath, options) => { |
| 26 | + if (!htmlPath.endsWith('.html')) { |
| 27 | + throw new Error(`Input file must have the '.html' extension: ${htmlPath}`) |
| 28 | + } |
| 29 | + if (!fs.existsSync(htmlPath)) { |
| 30 | + throw new Error(`Input file does not exist: ${htmlPath}`) |
| 31 | + } |
| 32 | + const outputPath = htmlPath.replace(/\.html$/, '.pdf') |
| 33 | + if (!options.force && fs.existsSync(outputPath)) { |
| 34 | + throw new Error(`Output file already exists: ${outputPath}`) |
| 35 | + } |
| 36 | + |
| 37 | + const browser = await chromium.launch({ channel: 'chrome' }) |
| 38 | + const page = await browser.newPage() |
| 39 | + |
| 40 | + const htmlPathURL = url.pathToFileURL(htmlPath).toString() |
| 41 | + console.log(`Processing ${htmlPathURL}...`) |
| 42 | + |
| 43 | + // Work around HUGO_RELATIVEURLS=false by rewriting the absolute URLs |
| 44 | + const baseURLPrefix = htmlPathURL.substring(0, htmlPathURL.lastIndexOf('/public/') + 8) |
| 45 | + await page.route(/^file:\/\//, async (route, req) => { |
| 46 | + // This _will_ be a correct URL when deployed to https://whatevers/, but |
| 47 | + // this script runs before deployment, on a file:/// URL, where we need to |
| 48 | + // be a bit clever to give the browser the file it needs. |
| 49 | + const original = req.url() |
| 50 | + if (original === htmlPathURL) { |
| 51 | + // Work around rerouted `.css` and `.js` files... Symptom: "has an |
| 52 | + // integrity attribute, but the resource requires the request to be CORS |
| 53 | + // enabled to check the integrity, and it is not. The resource has been |
| 54 | + // blocked because the integrity cannot be enforced." |
| 55 | + const body = |
| 56 | + fs.readFileSync(htmlPath, "utf-8") |
| 57 | + // strip out the `integrity="sha256-..."` attributes |
| 58 | + .replace(/(\/application\.[^"/]+") integrity="sha256-[^"]+"/g, "$1") |
| 59 | + await route.fulfill({ headers: { "Content-Type": "text/html" }, body }) |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + const url = |
| 64 | + original.startsWith(baseURLPrefix) |
| 65 | + ? original |
| 66 | + : original.replace(/^file:\/\/\/([A-Za-z]:\/)?(git-scm\.com\/)?/, baseURLPrefix) |
| 67 | + console.error(`::notice::Rewrote ${original} to ${url}`) |
| 68 | + await route.continue({ url }) |
| 69 | + }) |
| 70 | + |
| 71 | + await page.goto(htmlPathURL, { waitUntil: 'load' }) |
| 72 | + |
| 73 | + await page.pdf({ |
| 74 | + path: outputPath, |
| 75 | + format: 'A4', |
| 76 | + margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' }, |
| 77 | + }) |
| 78 | + await browser.close() |
| 79 | + |
| 80 | + if (options.insertPDFLink) insertPDFLink(htmlPath) |
| 81 | +} |
| 82 | + |
| 83 | +const args = process.argv.slice(2) |
| 84 | +const options = {} |
| 85 | +while (args?.[0].startsWith('-')) { |
| 86 | + const arg = args.shift() |
| 87 | + if (arg === '--force' || arg === '-f') options.force = true |
| 88 | + else if (arg === '--insert-pdf-link' || arg === '-i') options.insertPDFLink = true |
| 89 | + else throw new Error(`Unknown argument: ${arg}`) |
| 90 | +} |
| 91 | + |
| 92 | +if (args.length !== 1) { |
| 93 | + process.stderr.write('Usage: html-to-pdf.js [--force] [--insert-pdf-link] <input-file.html>\n') |
| 94 | + process.exit(1) |
| 95 | +} |
| 96 | + |
| 97 | +htmlToPDF(args[0], options).catch(e => { |
| 98 | + process.stderr.write(`${e.stack}\n`) |
| 99 | + process.exit(1) |
| 100 | +}) |
0 commit comments