Skip to content

Instantly share code, notes, and snippets.

@mahpah
Last active February 7, 2020 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahpah/585692e9882930158ee8eef80695a960 to your computer and use it in GitHub Desktop.
Save mahpah/585692e9882930158ee8eef80695a960 to your computer and use it in GitHub Desktop.
Convert html
/**
* Require external modules:
* npm install puppeteer tmp f
*/
const puppeteer = require('puppeteer');
const tmp = require('tmp');
const fileUrl = require('file-url');
module.exports = async function (result, htmlFile, pageSettings) {
const browser = await createBrowser();
const pdfPath = await createPdf(browser, htmlFile, pageSettings);
await browser.close();
result(null, pdfPath);
};
async function createBrowser() {
return await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
}
async function createPdf(browser, htmlFile, pageSettings) {
const page = await browser.newPage();
console.log(htmlFile);
console.log(pageSettings);
const tmpPdfFileName = tmp.tmpNameSync() + '.pdf';
await page.goto(fileUrl(htmlFile), {
waitUntil: 'networkidle2'
});
await page.pdf({
path: tmpPdfFileName,
landscape: pageSettings.layout === 'landscape',
format: pageSettings.pageSize,
margin: {
top: pageSettings.top,
left: pageSettings.left,
right: pageSettings.right,
bottom: pageSettings.bottom
},
printBackground: true
});
await page.close();
return tmpPdfFileName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment