Last active
February 7, 2020 02:45
-
-
Save mahpah/585692e9882930158ee8eef80695a960 to your computer and use it in GitHub Desktop.
Convert html
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
/** | |
* 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