打印时保持R Markdown语法高亮显示

时间:2012-09-02 23:15:33

标签: r markdown knitr rstudio

我担心会有这样的回应:“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”按钮并在Chrome或Safari中打开HTML,没有任何问题。如果我从浏览器中打印HTML,则所有语法突出显示都将丢失。

2 个答案:

答案 0 :(得分:9)

在对原始示例执行“编织”之后。您将在工作路径中使用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")

答案 1 :(得分:0)

我还发现了一个解决方案,即编织为HTML,在浏览器中预览html文件,然后突出显示所有内容并将其粘贴到MS Word文档中。从那里您可以导出为PDF或进行打印。不幸的是,它没有将所有图像复制到Word文档中。但是,如果您只需要语法高亮显示,而不是太担心图像或图表,那么此解决方案将非常简单。实际上,它复制的代码框比pandoc解决方案要好一些,但缺点是没有图像。

相关问题