简体   繁体   English

是否可以在 rmarkdown 呈现的 pdf 文档中包含 svg 图像?

[英]Is it possible to include svg image in pdf document rendered by rmarkdown?

I want an svg image to be embedded in an pdf document that I render by using rmarkdown.我希望将 svg 图像嵌入到我使用 rmarkdown 呈现的 pdf 文档中。 This doesn't seem possible, or do I miss something?这似乎不可能,还是我错过了什么? If it's not possible is there a way to first convert the .svg image to a .png before embedding it?如果不可能,有没有办法在嵌入之前先将 .svg 图像转换为 .png ?

In my rmarkdown file it looks like this (notice the two different kinds of inserting the image):在我的 rmarkdown 文件中,它看起来像这样(注意插入图像的两种不同类型):

```{r results="asis",eval=TRUE,echo=FALSE,message=FALSE, error=FALSE, warning=FALSE, comment = NA,fig.height=10}

cat("![](svg_file.svg)")

```

![](svg_file.svg)

Now we can simply use the cowplot library to read an image and plot it in R markdown.现在我们可以简单地使用 cowplot 库来读取图像并在 R markdown 中绘制它。

```{r figSvg,eval=TRUE,echo=FALSE,message=FALSE, error=FALSE, warning=FALSE,fig.height=10}

library(cowplot)
fig_svg<-cowplot::ggdraw()+cowplot::draw_image("http://jeroen.github.io/images/tiger.svg")
plot(fig_svg)

I found a solution that works for me.我找到了一个适合我的解决方案。 It is based on using the svg LaTeX package and some LaTeX code inside your Rmarkdown file.它基于在 Rmarkdown 文件中使用svg LaTeX 包和一些 LaTeX 代码。

This can be achieved in these main steps:这可以通过以下主要步骤实现:

  1. Include the svg package to the LaTeX preamble.svg包包含到 LaTeX 序言中。 This can be done using the Rmarkdown header.这可以使用 Rmarkdown 标头来完成。
  2. Make sure that LaTeX is called with the --shell-escape option enabled.确保在启用--shell-escape选项的情况下调用 LaTeX。 This can also be done using the Rmarkdown header.这也可以使用 Rmarkdown 标头来完成。
  3. Include your SVG image using \\includesvg{svg-image} inside your Rmarkdown text.在 Rmarkdown 文本中使用\\includesvg{svg-image}包含您的 SVG 图像。 Be careful, do not include the file extension .请注意,不要包含文件扩展名.

Make sure to use pdflatex as the LaTeX engine.确保使用pdflatex作为 LaTeX 引擎。 Other engines will probably work as well, but they will require different options...其他引擎可能也能工作,但它们需要不同的选项......

The following is a example that works in my machine, having a SVG image called svg-image.svg in the working directory.下面是一个在我的机器上工作的例子,在工作目录中有一个名为svg-image.svg的 SVG 图像。

---
output: 
  pdf_document:
    latex_engine: pdflatex
    pandoc_args: "--latex-engine-opt=--shell-escape"
header-includes:
   - \usepackage{svg}
---

\includesvg{svg-image}

I hope it helps!我希望它有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM