1

I have foo.Rnw file which uses the extrafont package for generating figures with text elements that use non-standard font families. After knitr calls pdflatex on my document, I want to run extrafont::embed_fonts on the resulting foo.pdf file.

I can do this manually, but is there a way to do this from within knitr? (e.g., some knitr package option I can set to automatically call extrafont::embed_fonts after it knits my file and runs it through pdflatex)

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
Jonathan Gilligan
  • 701
  • 1
  • 5
  • 21

1 Answers1

3

As explained in this answer, it is possible to modify the behavior of the "Compile PDF" button in RStudio by setting the YAML option knit. This allows to run arbitrary code when hitting the "Knit" button. Note that the code must be formatted as a one-liner and you need to use single quotes for character data (double quotes won't work).

I don't know the extrafont package, so here an example that crops the generated PDF. Calling extrafont::embed_fonts should work analogously:

---
knit: (function(inputFile, encoding) { rmarkdown::render(input = inputFile, encoding = encoding); knitr::plot_crop(paste0(basename(tools::file_path_sans_ext(inputFile)), '.pdf')) } )
output: pdf_document
---

```{r}
print("Hello world!")
```

It's actually pretty simple; the most complicated part is composing the output file name: (paste0(basename(tools::file_path_sans_ext(inputFile)), '.pdf') (see here).

Community
  • 1
  • 1
CL.
  • 14,577
  • 5
  • 46
  • 73
  • Nice for .Rmd. Is there anything comparable for .Rnw, which doesn't have YAML headers? – Jonathan Gilligan Sep 30 '16 at 01:18
  • @jgilligan Oh, sorry, I missed the `rnw` tag on your question. At the moment I don't know how to apply this to RNW, but I'll keep it at the back of my head. – CL. Sep 30 '16 at 08:29