Pet*_*ith 9 svg latex bookdown
我有一些 R markdown,其中包含以下代码:
```{r huff51, fig.show='hold', fig.cap='Design decisions connecting research purpose and outcomes [@huff_2009_designingresearchpublication p. 86].', echo=FALSE}
knitr::include_graphics('images/Huff-2009-fig5.1.svg')
```
Run Code Online (Sandbox Code Playgroud)
当使用 bookdown 生成 HTML 输出时,一切都按预期进行。
当使用 bookdown 生成 PDF 输出时,我收到一条错误消息! LaTeX Error: Unknown graphics extension: .svg.
这是可以理解的,因为 knitr 使用 Latex\includegraphics{images/Huff-2009-fig5.1.svg}来包含图像。所以,这本身并不是一个错误。
有没有更好的方法来包含 SVG 图像,这样我就不需要将其预处理为 PDF 或 PNG 等图像?
您可以创建一个辅助函数来将 SVG 转换为 PDF。例如,如果您rsvg-convert安装了系统包,则可以使用此功能包含SVG图形:
include_svg = function(path) {
if (knitr::is_latex_output()) {
output = xfun::with_ext(path, 'pdf')
# you can compare the timestamp of pdf against svg to avoid conversion if necessary
system2('rsvg-convert', c('-f', 'pdf', '-a', '-o', shQuote(c(output, path))))
} else {
output = path
}
knitr::include_graphics(output)
}
Run Code Online (Sandbox Code Playgroud)
您还可以考虑像magick(基于 ImageMagick)这样的 R 包来将 SVG 转换为 PDF。