Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer not rendering color, background color when I try to save PDF on disk

This is my node.js and HTML template code which creates a PDF from an HTML template. It's not putting in the colors.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("file:///D:/pdf_export/template/template.html");
    await page.pdf({
        path: 'output.pdf',
        printBackground: true
    });
    await browser.close();
})()
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>

    <body>
        <p style="color: red;">Hello World</p>
    </body>
</html>

When I open the output.pdf, it only shows 'Hello world' in black not in red.

like image 392
Rajan Sohal Avatar asked Mar 18 '20 09:03

Rajan Sohal


2 Answers

Puppeteer is just a library to drive Chrome/Chromium, so if anything goes wrong while using it, our best bet is to open Chromium with puppeteer.launch({headless:false}) and debug there.

Set your page css in <style></style> tag.

You can solve the issue with the following CSS code:

html {
  -webkit-print-color-adjust: exact;
}
p {
  color: #FF0000; 
}
like image 181
Deep Kakkar Avatar answered Nov 12 '22 17:11

Deep Kakkar


For me none of the solutions I found on stackoverflow worked. I almost "lost hope". But after playing around with all the info I found, all that really mattered was:

  1. the printBackground option has to be set to TRUE, e.g.: page.pdf({ path: "./my.pdf", printBackground: true });
  2. add to your background or color values !important, e.g.:
p {
  color: #FF0000 !important; 
}

That's it.

P.S. regarding the -webkit-print-color-adjust: exact; it was useless in my case. I have currently Puppeteer v5.5.0.

like image 31
nostop Avatar answered Nov 12 '22 18:11

nostop