I am using puppeteer
(headless Chrome) to render an .html generated by an RMarkdown script to .pdf. However, puppeteer
doesn't seem to respect my color
and background-color
style settings. The problem doesn't exist when rendering pages off the web, suggesting it's the interaction between puppeteer
and RMarkdown
.
Consider the following test.Rmd
script:
---
title: "Testing colors"
output: html_document
---
<style>
html {
-webkit-print-color-adjust: exact;
}
h4 {color: blue;}
</style>
#### Blue heading
<div style="color:red">This text is red</div>
<div style="background-color:red">This text has red background</div>
We can render it to test.html
by calling rmarkdown::render( "test.Rmd", output_file="test.html" )
in R. Note the -webkit-print-color-adjust
setting; it is often recommended as a solution to color-related problems, but I found that it has no effect in my case.
Following puppeteer tutorials, I put together the following render.js
:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({width: 400, height: 200});
await page.goto('file:///home/sokolov/test/puppeteer/test.html');
await page.screenshot({path: 'test.png'});
await page.pdf({path: 'test.pdf', printBackground: true});
await browser.close();
})();
Running node render.js
from the command line produces test.png
and test.pdf
. The former looks exactly how you would expect:
However, the .pdf
loses all color specifications:
If I replace the url in my render.js
with an external page (e.g., https://www.w3schools.com/css/css_background.asp
), the page renders correctly in both .png
and .pdf
formats. Specifying printBackground: true
was key to making it work for this external page, but it seems to have no effect of my local test.html
.
Any thoughts on how to get the colors working?
P.S. To briefly address the question of why I'm not simply using output: pdf_document
in my .Rmd
, I wanted to note that the real RMarkdown document I'm working with uses flexdashboard
layout, which doesn't play nicely with knitr. Most of the tutorials I've read suggest using a headless browser to render the final .html
to .png
/.pdf
. The solution is working well for me, except for the loss of color styles.