Skip to content

Instantly share code, notes, and snippets.

@Faizanq
Created July 16, 2019 14:19
Show Gist options
  • Save Faizanq/e01795e8e761aed1fd7ad17e7c01d4fe to your computer and use it in GitHub Desktop.
Save Faizanq/e01795e8e761aed1fd7ad17e7c01d4fe to your computer and use it in GitHub Desktop.
module.exports.generatePdf = async ()=>{
async function Html() {
try {
const data = {
name: 'Faizan'
}
const templatePath = Path.resolve('./views/invoice.handlebars');
const content = await ReadFile(templatePath, 'utf8')
// compile and render the template with handlebars
const template = Handlebars.compile(content)
return template(data)
} catch (error) {
throw new Error('Cannot create invoice HTML template.')
}
}
async function startBrowser() {
const browser = await Puppeteer.launch();
const page = await browser.newPage();
return {browser, page};
}
async function closeBrowser(browser) {
return browser.close();
}
async function html2pdf() {
const {browser, page} = await startBrowser();
const html = await Html()
await page.setContent(html)
await page.setContent(html) //with double work fine but not one line need to check later
// await page.emulateMedia('screen');
// await page.pdf({path: 'page.pdf'}); //for file
let buffer = await page.pdf(); //for buffer
return buffer;
}
(async () => {
await html2pdf();
process.exit(1);
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment