Skip to content

Instantly share code, notes, and snippets.

@spencerldixon
Created November 8, 2019 13:33
Show Gist options
  • Save spencerldixon/fb8600103e751872fdfcda4031c62e62 to your computer and use it in GitHub Desktop.
Save spencerldixon/fb8600103e751872fdfcda4031c62e62 to your computer and use it in GitHub Desktop.
html2pdf with Puppeteer
'use strict';
const puppeteer = require('puppeteer');
const fs = require('fs'); //Filesystem
let content = fs.readFileSync(process.argv[2], "utf-8");
const createPdf = async() => {
let browser;
try {
browser = await puppeteer.launch({args: [
'--no-sandbox',
'--disable-setuid-sandbox'
]});
const page = await browser.newPage();
await page.setContent(content, {waitUntil: 'networkidle0'});
await page.setViewport({
width: 1024,
height: 768
})
await page.waitFor(250);
await page.pdf({
path: process.argv[3],
format: 'A4',
margin: { top: 36, right: 36, bottom: 20, left: 36 },
printBackground: true
});
} catch (err) {
console.log(err.message);
} finally {
if (browser) {
browser.close();
}
process.exit();
}
};
createPdf();
@spencerldixon
Copy link
Author

If you're deploying to heroku, you'll need the node and puppeteer buildpacks as mentioned in this post: https://www.forsbergplustwo.com/blogs/news/pdf-generation-with-chrome-headless-in-ruby-using-puppeteer-on-heroku

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment