Created
November 8, 2019 13:33
-
-
Save spencerldixon/fb8600103e751872fdfcda4031c62e62 to your computer and use it in GitHub Desktop.
html2pdf with Puppeteer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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