有啥方法可以打印 rmarkdown 表而不丢失颜色?
Posted
技术标签:
【中文标题】有啥方法可以打印 rmarkdown 表而不丢失颜色?【英文标题】:Is there any way to print rmarkdown table without losing colors?有什么方法可以打印 rmarkdown 表而不丢失颜色? 【发布时间】:2016-04-13 04:08:11 【问题描述】:当我尝试打印由 knitr 生成的 html 时,打印页面会丢失所有颜色和格式。有什么方法可以在不丢失格式的情况下打印 HTML 输出?我尝试使用this 建议的css 来解决这个问题,但是没有任何区别。
styles.css
@media print
body -webkit-print-color-adjust: exact;
@media print
table -webkit-print-color-adjust: exact;
降价代码:
---
title: "Habits"
output:
html_document:
css: styles.css
---
```r, echo = FALSE
df <- data.frame(
id = 1:10,
name = c("Bob", "Ashley", "James", "David", "Jenny",
"Hans", "Leo", "John", "Emily", "Lee"),
age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
stringsAsFactors = FALSE)
```
``` r, eval = TRUE, echo = FALSE, results='asis'
library(formattable)
formattable(df, list(
age = color_tile("white", "orange"),
grade = formatter("span",
style = x ~ ifelse(x == "A", style(color = "green", font.weight = "bold"), NA)),
final_score = formatter("span",
style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
registered = formatter("span",
style = x ~ style(color = ifelse(x, "green", "red")),
x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
))
```
【问题讨论】:
到目前为止,我发现我需要覆盖 bootstrap.css @media 打印设置,但仍然不确定如何。 Related. 【参考方案1】:一个不能完全解决问题但允许您打印带有颜色的降价表的解决方案是将可格式化表导出为图像,以便实际降价表上的表是 png 文件类型。下面是一个函数,您可以将其应用于您的表。
export_formattable <- function(f, file, width = "100%", height = NULL,
background = "white", delay = 0.2,
width_svg=720, height_svg=740)
w <- as.htmlwidget(f, width = width_svg, height = height_svg)
path <- html_print(w, background = background, viewer = NULL)
url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path)))
webshot(url,
file = file,
selector = ".formattable_widget",
delay = delay)
将此应用于您的表:
formattble_table <- formattable(df, list(
age = color_tile("white", "orange"),
grade = formatter("span",
style = x ~ ifelse(x == "A", style(color = "green", font.weight = "bold"), NA)),
final_score = formatter("span",
style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
registered = formatter("span",
style = x ~ style(color = ifelse(x, "green", "red")),
x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
))
export_formattable(formattble_table, "formattble_table.png")
这篇文章有助于找到导出表的解决方案:Command for exporting/saving table made with Formattable package in R。
为 faaabyan - https://***.com/users/4065921/faaabyan 找到此导出解决方案干杯。
【讨论】:
以上是关于有啥方法可以打印 rmarkdown 表而不丢失颜色?的主要内容,如果未能解决你的问题,请参考以下文章