When an Rnw
file is converted to PDF
with RStudio and knitr
, the code blocks have a pleasant grey background colour (like they do here at SO). When I convert a md
file to PDF
, the background colour is white and I can't seem to change it. The knitr code decoration option background
is only for LaTeX and has no effect in md
.
How can I set a background colour for code blocks in the PDF
I get from my md
file? I see in some related questions that editing the markdown.css file might be relevant, but I'm not sure if that applies here since there's no html file in between the md
and PDF
files.
This effect can be reproduced using the knitr examples: Rnw source: knitr-minimal.Rnw and markdown source: 001-minimal.Rmd.
To convert Rnw
to PDF
I just click the 'compile PDF' button in RStudio. Here's what I do to convert md
to PDF
:
# Load packages
require(knitr)
require(markdown)
setwd("C:/Users/.../Desktop/")
# Process .md and .pdf files
filen <- "myfile"
knit(paste0(filen,".md"))
system(paste0("pandoc -s ", paste0(filen,"-out.md"), " -t latex -o ", paste0(filen,".pdf")))
Is there another way to convert md
to PDF
so I can get a coloured code background?
Since you're already set up with Pandoc, you should be able to achieve this using Pandoc's --highlight-style
argument. From the docs:
--highlight-style=STYLE Specifies the coloring style to be used in highlighted source code. Options are pygments (the default), kate, monochrome, espresso, zenburn, haddock, and tango.
If you're not specifying the language that each code block contains within the markdown file, you might also have to set the --indented-code-classes
argument:
--indented-code-classes=CLASSES Specify classes to use for indented code blocks–for example, perl,numberLines or haskell. Multiple classes may be separated by spaces or commas.
From memory, I think this might require a latex package like fancyvrb
, so you might have to install that before it works.
Marius' answer is exactly what I was after. Since comments can't take images, I'm pasting a few screenshots here in case others are curious about this.
To get code backgrounds in the PDF
generated from the md
, I adjusted my code like so:
# Load packages
require(knitr)
require(markdown)
setwd("C:/Users/.../Desktop/")
# Create .md and .pdf files
filen <- "test"
knit(paste0(filen,".md"))
system(paste0("pandoc -s ", paste0(filen,"-out.md"), " -t latex -o ", paste0(filen,".pdf"), " --highlight-style=tango -S"))
In testing the seven pandoc
highlighting options, I found that only three give code backgrounds. Here are screenshots of the PDFs generated with each of the three options, for future reference.
This is tango, the one that best matches what I'm after with the light grey:
And this is zenburn: And this is espresso
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With