Skip to content

Instantly share code, notes, and snippets.

@felddy
Last active March 10, 2020 02:18
Show Gist options
  • Save felddy/21df29545a4312105b08f8a698eb3ba5 to your computer and use it in GitHub Desktop.
Save felddy/21df29545a4312105b08f8a698eb3ba5 to your computer and use it in GitHub Desktop.
Rendering HTML reports with puppeteer.
yarn install
./render.js https://fivethirtyeight.com 538.pdf
{
"dependencies": {
"docopt": "^0.6.2",
"puppeteer": "^2.0.0"
}
}
#!/usr/bin/env node
/* eslint-disable no-console */
const doc = `
Render webpages to a PDF file.
Usage:
render.js [options] <url> <pdf-filename>
Options:
-b, --print-background Print backgrounds.
-f, --format=<size> Set output format size [default: Letter].
-h, --help Show this screen.
-v, --verbose Output status messages.
--version Show version.
`;
const puppeteer = require("puppeteer");
const { docopt } = require("docopt");
const options = docopt(doc, { version: "0.0.1" });
function log(msg) {
if (options["--verbose"]) {
console.log(msg);
}
}
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
log("Rendering: " + options["<url>"]);
await page.goto(options["<url>"], {
waitUntil: "networkidle0"
});
await page.pdf({
path: options["<pdf-filename>"],
format: options["--format"],
printBackground: options["--print-background"]
// preferCSSPageSize: true
});
await browser.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment