Last active
June 15, 2020 08:53
-
-
Save adeelibr/57081ec24b634b4d161e405ae3bf6d78 to your computer and use it in GitHub Desktop.
createPdf.js script for NodeJS FS & 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
const fs = require('fs'); | |
const puppeteer = require('puppeteer'); | |
// Build paths | |
const { buildPathHtml, buildPathPdf } = require('./buildPaths'); | |
const printPdf = async () => { | |
console.log('Starting: Generating PDF Process, Kindly wait ..'); | |
/** Launch a headleass browser */ | |
const browser = await puppeteer.launch(); | |
/* 1- Ccreate a newPage() object. It is created in default browser context. */ | |
const page = await browser.newPage(); | |
/* 2- Will open our generated `.html` file in the new Page instance. */ | |
await page.goto(buildPathHtml, { waitUntil: 'networkidle0' }); | |
/* 3- Take a snapshot of the PDF */ | |
const pdf = await page.pdf({ | |
format: 'A4', | |
margin: { | |
top: '20px', | |
right: '20px', | |
bottom: '20px', | |
left: '20px' | |
} | |
}); | |
/* 4- Cleanup: close browser. */ | |
await browser.close(); | |
console.log('Ending: Generating PDF Process'); | |
return pdf; | |
}; | |
const init = async () => { | |
try { | |
const pdf = await printPdf(); | |
fs.writeFileSync(buildPathPdf, pdf); | |
console.log('Succesfully created an PDF table'); | |
} catch (error) { | |
console.log('Error generating PDF', error); | |
} | |
}; | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment