25

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.

Rajan Sohal
  • 413
  • 1
  • 5
  • 9

2 Answers2

69

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; 
}
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
48

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
nostop
  • 743
  • 5
  • 9
  • 4
    Thanks man, you saved some hairs from my head with the "printBackground: true" – Foxlab Feb 19 '21 at 13:50
  • Perfect! This a first time I use `puppeteer` and you same me hours of tinkering about why no background is in the generated PDF. Just a note: I tested this with `product: 'firefox'` and it works as expected! ;) – tukusejssirs Mar 28 '21 at 16:51
  • the "printBackground"-Option is the important part here. Otherwise no "background-color" stuff is printed ad all.. Thank you! – Stefan Nov 24 '21 at 13:13
  • 1
    "printBackground" is needed, but nothing worked without also adding "!important" for me as well. – akaspick Jan 17 '22 at 01:42
  • "printBackground: true" worked for me. Thank you! – pradeep Nov 18 '22 at 06:39