在 YAML 标头后面添加以下内容:
<style>
@media print {
font[color="green"] {
color: #00ff00!important;
-webkit-print-color-adjust:exact;
}
font[color="red"] {
color: #ff0000!important;
-webkit-print-color-adjust:exact;
}
}
</style>
问题是 RStudio 的默认 R markdown 模板使用 Bootstrap 及其版本bootstrap.min.css
has:
@media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
在里面。这是一个相当“破坏性”的媒体查询*
导致这些设置被应用到all标签和color: #000 !important;
means “没有颜色适合你!”当您打印文档时。我理解这背后的情感(拯救地球+墨粉/墨水成本),但如果你打印为 PDF,那就毫无意义了。
不幸的是,没有用于打印到 PDF 的超针对性媒体查询,因此当您将网页打印到 PDF 时,会应用通用的“打印”媒体查询,而这些无意识的、包罗万象的媒体查询就会接管。
您面临的问题是,您需要非常具体地定位任何其他标签才能覆盖这些设置。这意味着将您自己的 CSS 类添加到您在 Rmds 中生成的任何内容中,或者熟悉“检查元素”直到您掌握所有内容。
However,如果您喜欢冒险,可以将 YAML 标头修改为:
output:
html_document:
self_contained: false
当您渲染为 HTML 时,它将创建一个目录,其中包含各种组件的子目录,而不是将它们进行 base64 编码到一个大文档中。
我将我的文档命名为forso.Rmd
这意味着它创建了一个名为forso_files
并在其下放置子目录。
打开主 HTML 文件并向下滚动,直到看到类似以下内容:
<script src="forso_files/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="forso_files/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="forso_files/navigation-1.1/tabsets.js"></script>
改变这个:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
to:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet" />
Edit bootstrap.css
, 去除color: #000 !important;
行并添加-webkit-print-color-adjust:exact;
线。保存副本bootstrap.css
在其他地方,因为它会在未来的渲染中被压缩(即您需要在每次渲染时将其复制回来)。
你不能仅仅链接到一个单独的 CSS 文件,并使用更少脑死亡的打印媒体查询,因为color: #000 !important;
影响所有标签,这要归功于*
目标,你不能只是将其重置为initial
或继承`,因为这也会让他们变黑。
您最后的(可能也是最好的)选择是制作自己的 R Markdown 模板(请参阅https://github.com/hrbrmstr/markdowntemplates https://github.com/hrbrmstr/markdowntemplates了解更多信息)并避免在其中放置全面的印刷媒体查询。