Skip to content

Instantly share code, notes, and snippets.

@ChrisAichinger
Last active August 16, 2022 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ChrisAichinger/151050a7c16070cdbd84e2697f7332d1 to your computer and use it in GitHub Desktop.
Save ChrisAichinger/151050a7c16070cdbd84e2697f7332d1 to your computer and use it in GitHub Desktop.
htmlpdf.js -- Convert HTML to PDF using Google Chrome/Chromium
#!/usr/bin/env node
// htmlpdf.js -- Convert HTML to PDF using Google Chrome/Chromium
// Usage:
// node htmlpdf.js input.html output.pdf
// node htmlpdf.js https://google.com output.pdf
//
// Using Chrome/Chromium via puppeteer provides support for modern web
// technologies (CSS grid, etc.) and pixel-perfect rendering.
// Thus, this script correctly transforms websites where PhantomJS or wkhtmltopdf fail.
//
// We use CSS paper layout and margins by default, this can be changed in `options` below.
// Cf. https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagepdfoptions
//
// Published by Christian Aichinger (https://greek0.net/) on
// https://gist.github.com/ChrisAichinger/151050a7c16070cdbd84e2697f7332d1
// Based on https://www.npmjs.com/package/pdf-puppeteer, thus licensed under 3-clause BSD.
const fs = require('fs');
const puppeteer = require('puppeteer');
const process = require('process');
const convertHTMLToPDF = async (url, output, options=null, puppeteerArgs=null) => {
let browser;
if (puppeteerArgs) {
browser = await puppeteer.launch(puppeteerArgs);
} else {
browser = await puppeteer.launch();
}
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle0'});
const result = await page.pdf(options);
await browser.close();
return result;
};
let input = process.argv[2];
if (!input.includes('://')) {
input = 'file:///' + fs.realpathSync(input); // file:// urls must be absolute.
}
const output = process.argv[3];
const options = {
format: 'A4',
path: output,
preferCSSPageSize: true,
};
convertHTMLToPDF(input, output, options).catch(error => console.log(error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment