On my website, students have the ability to create their own notes using a RichText editor where the content can be quite complex. I want to provide them with an option to download these notes as a PDF file. To achieve this, I am planning to use the "puppeteer" tool. When I tested it by navigating to a specific page on my site, the outcome looked promising. However, for the note-printing functionality, I don't want to navigate to a separate page; instead, I just want to pass an HTML snippet of a div
that contains the notes. The issue I'm facing is that when I do this, the styles are not preserved and the final output appears very poorly formatted. Since I am using NextJS with Tailwind CSS, with many styles being added through link
tags, I suspect that puppeteer may not recognize them resulting in the style discrepancies. What could be a potential solution to ensure that the styles are applied correctly? Here is my current implementation:
async generatePdfFromHtml(user: UserEntity, data: InputGetPdfDto) {
const browser = await puppeteer.launch({ executablePath: puppeteer.executablePath('chrome') });
const page = await browser.newPage();
const html = data.html;
await page.setContent(html, { waitUntil: 'networkidle2' });
console.log(html);
const fileName = `element-${Date.now()}.pdf`;
const filePath = path.join('output', fileName);
await page.pdf({
path: filePath,
format: 'A4',
printBackground: true,
timeout: 0,
});
await browser.close();
return filePath;
}
MORE DETAILS
My website structure resembles the following:
<html lang="en" class="dark" style="color-scheme: dark;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/_next/static/css/app/layout.css?v=1717793996045" data-precedence="next_static/css/app/layout.css">
// content
</html>
I aim to include a button labeled "Download as PDF", which will convert a div
with the ID notes
into a PDF file. My goal is to retain all the original styles used on the website that are linked via link
tags. Currently, the html
being used consists simply of the outerHTML
of the div#notes
. Naturally, when I utilize page.setContent(html)
, the result appears messy due to the absence of styles. How can I rectify this issue?