在 R 中使用 pagedown 从 HTML 转换为 pdf

Using pagedown to convert from HTML to pdf in R

第一次使用pagedown

你能帮帮我吗?

这是我的 .Rmd 代码:

---
title: "Table"
output:
  html_document:
    css: "test.css"
---

```{r}
library(knitr)
data(iris)
kable(iris)
```  

这是我的 .css 文件:

.main-container { 
     max-width: 1600px !important;
 } 
 tr:nth-child(even) {
     background-color: #f2f2f2;
 }
 th {
     background-color: #FF6319;
     color: white;
     font-size: 12px;
 }
 tbody {
     font-size: 12px;
 }
 hr {
     page-break-after: always;
 }

当我设置命令 pagedown::chrome_print('C:/Users/user/Downloads/myfile.html') 时,会创建 pdf 输出,但它不会保持 css 样式。

我错过了什么?

有什么帮助吗?

谢谢!

此行为来自打印 media queryrmarkdown::html_document() 输出格式为打印和屏幕定义了不同的 CSS 规则。其次,pagedown::chrome_print()函数使用打印媒体样式生成PDF。

rmarkdown::html_document() 输出格式依赖于 Bootstrap 3.3.5,它为印刷媒体定义了一些特定规则,see the source code

更准确地说,在源代码中,有这样的声明:

@media print {
  .table td, .table th {
    background-color: #fff !important;
  }
}

这些规则覆盖印刷媒体问题中定义的 CSS 规则。

为了获得预期的行为,您必须使用更高的 specificity.

覆盖这些内置 CSS 规则

这个修改后的样式表应该可以解决问题:

.main-container { 
     max-width: 1600px !important;
 } 
 .table tbody tr:nth-child(even) {
     background-color: #f2f2f2 !important;
 }
 .table thead th {
     background-color: #FF6319 !important;
     color: white !important;
     font-size: 12px;
 }
 tbody {
     font-size: 12px;
 }
 hr {
     page-break-after: always;
 }