PDF font size issue using HTML with Puppeteer
Asked Answered
H

2

7

I am trying to generate a PDF in browser(chrome v8) using HTML by sending it to puppeteer. The html is getting generated using ejs since there is dynamic content for some of the sections of the PDF. The dynamic content includes images,html tables(number of rows and columns are dynamic) and text.

In the HTML I have defined css within the style tag to format the content.

While the font-size seems to be coming from the style tag - the entire content seems to be getting compressed/contracted for some combinations of content. It looks like one PDF content was generated at a 100% zoom (normal sized) and the other at 80% zoom (where everything looks smaller).

I tried removing the img tags (no extra CSS Styling is given) - that solved the problem for combination of data.

Also the content on the right is getting cut in some cases - I have tried giving the body tag in the html a width of 100% but that has not solved the problem.

Viewing the HTML generated by EJS in the browser as a pure HTML file - shows no difference between the cases where the PDF shows a change in size.

Any pointers in solving this would be appreciated.

Font-size is set as

* {
    Font-size: 16px;
}

Puppeteer code snippets are given below:

const browser = await puppeteer.launch({
           args: ['--no-sandbox'],
           headless: true
       });


await page.setContent(bodyHtml, {
           waitUntil: 'networkidle0'
       });

var options = {
           headerTemplate: headerHtmlWithStyles,
           footerTemplate: footerHtmlWithStyles,
           displayHeaderFooter: true,
                    margin: {
               top: "195px",
               right: "64px",
               bottom: "100px",
               left: "64px"
           },
           
           printBackground: false,
           path: pdfPath,
           format: 'A4',
           preferCSSPageSize: false
       }


await page.emulateMediaType("screen");
       await page.pdf(options);

Highball answered 10/2, 2021 at 13:35 Comment(2)
Did you end up finding out how to fix this?Emit
Any luck on this issue?Syllabism
S
0

its late..but To solve

Also the content on the right is getting cut in some cases - I have tried giving the body tag in the html a width of 100% but that has not solved the problem.

use below width in your page.pdf options

var maxWidth = await page.evaluate(() => Math.max(document.body.scrollWidth, document.documentElement.clientWidth));

Syllabism answered 27/4, 2022 at 12:27 Comment(0)
L
0

I solved the scale content with next code:

After page.setContent...

await page.addStyleTag({
  content: `
        * {
            overflow-x: hidden !important; 
        }
    `
});
Landlubber answered 22/2 at 3:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.