在打印时保留 R Markdown 语法高亮

11

我担心的回答是:"Markdown 的初衷就是简单,它不能做到这一点",但询问从来不会伤害任何人。

在编写 R Markdown 文档时,我可以在浏览器中查看 HTML 文件并且它看起来很棒。但是当我尝试打印它,无论是在纸上还是作为 PDF,图形中的颜色都会被打印出来,但是语法高亮却没有了。是否有一种方法可以在打印时保持语法高亮?

例如:

Minimal Example
=====

This text looks great in the file and the plot prints in color, but see commented code     below.

```{r}
# this commented line will be green in the HTML file, but will be black when I print it
z <- cor(mtcars) 
require(lattice) # 'require' will be blue in the HTML file, but will be black when I print it
levelplot(z)
```

在RStudio中,我点击“Knit HTML”按钮将代码转化为HTML格式后,用Chrome或Safari打开HTML没有问题。但是,如果从浏览器中打印HTML,所有的语法高亮都会丢失。


你能提供一个最小化可复现的工作流程示例吗? - mnel
什么样的R Markdown?knitr吗? - David Robinson
有没有其他使用 R Markdown 的方法?请详细说明。 - Zoë Clark
1
总有许多种方法可以解决问题。对于R Markdown,您还可以使用pander - mnel
在这里,使用knit2HTML按钮非常关键。问题在于markdown::markdowntoHTML突出显示的方式。 - mnel
2个回答

9

在对原始的example.Rmd文件进行“编织”后,您将在工作路径中得到一个example.md文件,然后使用pandoc...

# for pdf (you need to have latex installed)
system( "pandoc example.md -o example.pdf")

# for syntax-highlight persistant html
system("pandoc example.md -o example.html -s -S")

0
一个我也发现的解决方法是将R代码转换成HTML,预览HTML文件,然后选中全部内容并将其粘贴到MS Word文档中。从那里,您可以将其导出为PDF或打印。不幸的是,它并不能将所有图片复制到Word文档中。但如果您只需要语法高亮,并且不太关心图片或绘图,那么这个解决方案就相当简单。它实际上比pandoc解决方案更好地复制了代码框,但缺点是没有图片。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接