Convert Html to Pdf with CSS
I have been trying to follow the below medium link to create PDF from html and I came to know some problems and solutions.
Problems:
- My CSS were not getting applied on the generated PDF
- Also I want to know whether my page has been loaded before I do the conversion.
- I want to get all console.log messages to see if my page has any errors.
Solutions:
- Use printBackground: true option in pdf generation api call.
- Use Inline CSS in html document.
- Use events on page to get console logs and loading status.
Code snippet:
const templateFile = fs.readFileSync(resumeTemplatePath, ‘utf8’);
const template = hb.compile(templateFile, { strict: true });
const result = template({name: ‘Arun Rajeevan’, title: ‘Cloud developer’});
const browser = await puppeteer.launch();
const page = await browser.newPage();
// We set the page content as the generated html by handlebars
page.once(‘load’, async() => {
console.log(‘Page loaded!’);
await page.pdf({ path: ‘resume.pdf’, format: ‘A4’, printBackground: true });
await browser.close();
});
page.on(‘console’, msg => {
for (let i = 0; i < msg.args().length; ++i)
console.log(`${i}: ${msg.args()[i]}`);
});