Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer & Google Chrome headless: influence of CSS @media on rendered PDF

I am using Puppeteer to render PDF out of HTML pages.

I specify media type to be 'screen' before rendering to PDF:

await page.emulateMedia('screen');

Let's assume I have an HTML page in which the <body> element has white background.

Under these conditions, am I right in expecting that styling of this kind:

@media screen {
  body {
    background: #ff0000;
  }
}

will make Puppeteer render a PDF where the element will have the background coloured #ff0000?

I am asking because it does not work on my machine, and I want to eliminate any known issues or other problems.

like image 255
ACEG Avatar asked Sep 14 '25 01:09

ACEG


1 Answers

You are correct in your assumption, but make sure that the printBackground option in page.pdf() is set to true before attempting to print.

Otherwise, the background colors and graphics will not be printed.

await page.emulateMedia('screen');

await page.pdf({
  path: 'example.pdf',
  printBackground: true,
});
like image 108
Grant Miller Avatar answered Sep 16 '25 17:09

Grant Miller