【发布时间】:2018-11-30 23:35:24
【问题描述】:
我正在使用puppeteer(无头 Chrome)将 RMarkdown 脚本生成的 .html 呈现为 .pdf。但是,puppeteer 似乎并不尊重我的color 和background-color 样式设置。网页渲染时不存在这个问题,提示是puppeteer和RMarkdown之间的交互。
考虑以下test.Rmd 脚本:
---
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>
我们可以通过在 R 中调用rmarkdown::render( "test.Rmd", output_file="test.html" ) 将其渲染为test.html。注意-webkit-print-color-adjust 设置; it is often recommended作为颜色相关问题的解决方案,但我发现对我的情况没有效果。
在puppeteer tutorials之后,我整理了以下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();
})();
从命令行运行node render.js 会生成test.png 和test.pdf。前者看起来完全符合您的预期:
但是,.pdf 丢失了所有颜色规范:
如果我将 render.js 中的 url 替换为外部页面(例如,https://www.w3schools.com/css/css_background.asp),则该页面以 .png 和 .pdf 格式正确呈现。指定 printBackground: true 是使其适用于此外部页面的关键,但它似乎对我的本地 test.html 没有影响。
对如何使颜色起作用有什么想法吗?
PS 为了简要解决我为什么不简单地在我的.Rmd 中使用output: pdf_document 的问题,我想指出我正在使用的真正的 RMarkdown 文档使用 @987654353 @布局,其中doesn't play nicely with knitr。我读过的大多数教程都建议使用无头浏览器将最终的.html 渲染为.png/.pdf。除了颜色样式丢失之外,该解决方案对我来说效果很好。
【问题讨论】:
标签: r r-markdown knitr puppeteer