Search code examples
ruby-on-railspdf-generationchromiumgrover-gem

rendering colours in PDF generation


two snippets of code are leading to the same result

<span style='color: rgb(255, 0, 0); ' >  [...]</span>


<div class='tree_vertical_father'> [...] </div>

*where*
.tree_vertical_father {
  background-color: rgba(0, 0, 255, 0.07);
}

background color is not applied and the color of the font is black.

The PDF is being generated with the grover gem that uses pupetter and thus chromium to generate a view then converted to a PDF.

When the view is generated in the browser, all colours are rendered as expected.

what is required to make Chromium accept the color styling?


Solution

  • Watch for media type, if you have it set to screen it will not show in pdf, which by default is print:

    <span style="color: rgb(255, 0, 0);">[...]</span>
    <div class="tree_vertical_father">[...]</div>
    
    <!--                         vvvvvvvv -->
    <style type="text/css" media="screen">
      .tree_vertical_father {
        background-color: rgba(0, 0, 255, 0.07);
      }
    </style>
    

    Backgrounds are off by default:

    Grover.new("http://localhost:3000",
      path: "localhost.pdf",
      print_background: true,    # enable backgrounds
      emulate_media: "screen"    # set media if needed
    ).to_pdf
    

    https://github.com/Studiosity/grover?tab=readme-ov-file#configuration

    https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.pdfoptions.md#properties