Knitr hook to postprocess pdf output?

最后都变了- 提交于 2019-12-11 04:12:36

问题


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)


回答1:


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).



来源:https://stackoverflow.com/questions/39713618/knitr-hook-to-postprocess-pdf-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!