4

I am using Headless Chrome to render HTML into PDFs, but background color rendering in PDFs only seems to work on certain webpages.

This is the library I am using: https://github.com/chrome-php/headless-chromium-php

For the following code, if I change $url to https://www.hovec.co.uk/ then it does not render any background colors or images, and yet it works for the BBC site.

$browserFactory = new BrowserFactory("/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"); //thats my local Chrome

    $browser = $browserFactory->createBrowser([
      'windowSize' => [794, 1122]
    ]);

    $url='https://www.bbc.co.uk/';
    //$url='https://www.hovec.co.uk/';

    // creates a new page and navigate to $url
    $page = $browser->createPage();
    $page->navigate($url)->waitForNavigation();
    $page->pdf(['printBackground'=>true, 'marginTop' => 0.0, 'marginBottom' => 0.0, 'marginLeft' => 0.0, 'marginRight' => 0.0])->saveToFile($filepath);
    $browser->close();

Any help with this would be much appreciated!

gillarf
  • 114
  • 9
  • the variable $filepath is defined? and can apache write in that directory? – Emiliano Jan 15 '20 at 21:22
  • Hi @Emiliano - yes the filepath is defined and the PDF is generated, but it has no background colours – gillarf Jan 17 '20 at 12:04
  • I tried but I can't probably is the conversion between html and pdf that is not ready yet, there is not a simple way of create a pdf that be equal to html not for now but maybe in a future – Emiliano Jan 17 '20 at 21:11
  • I stumbled upon a similar problem I using headless chromium (`chrome-aws-lambda`) and I noticed when I convert HTML to PDF `background-color` is ignored? I dunno. Really annoying and there is little to no documentation available. I'm wondering is that some configuration problem. However, previously I used PhantomJS and that did render all okay and apparently PhantomJS is an older, not maintained any more project... – iaforek Apr 10 '20 at 07:09

1 Answers1

3

Add this style to HTML page:

    <style>
        html { -webkit-print-color-adjust: exact; }
    </style>

Credits: https://stackoverflow.com/a/60736572/3013633

iaforek
  • 2,860
  • 5
  • 40
  • 56