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(); |
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
Parses a .html file to a string, and then converts to PDF. Set up for optimal sizing with A4 pages. If using with Rails, create a custom pdf layout that has no margins or containers, and save the html file, you can the run it through the script as below.
Usage
node pdf.js input_file.html output_file.pdf
If you're adding this script to rails and wanting to pass in a string of HTML instead of a file, place the script in the
vendors/assets/javascript
directory and remove line 6 that parses from a file, instead just take theprocess.argv[2]
as a string and set the content to that.