rdatasculptor
rdatasculptor

Reputation: 8447

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

In my rmarkdown file it looks like this (notice the two different kinds of inserting the image):

```{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)

Upvotes: 18

Views: 11428

Answers (3)

library(rsvg)
```{r fig2, fig.cap="desc"}
# Path to your SVG file
svg_file <- "Picture1.svg"

# Convert SVG to PNG (or PDF) for PDF output
pdf_file <- tempfile(fileext = ".pdf")
rsvg::rsvg_pdf(svg_file, pdf_file, )
knitr::include_graphics(pdf_file)
```

Upvotes: 0

Penning Yu
Penning Yu

Reputation: 181

Now we can simply use the cowplot library to read an image and plot it in 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)

Upvotes: 10

guyik
guyik

Reputation: 308

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.

This can be achieved in these main steps:

  1. Include the svg package to the LaTeX preamble. This can be done using the Rmarkdown header.
  2. Make sure that LaTeX is called with the --shell-escape option enabled. This can also be done using the Rmarkdown header.
  3. Include your SVG image using \includesvg{svg-image} inside your Rmarkdown text. Be careful, do not include the file extension.

Make sure to use pdflatex as the LaTeX engine. 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.

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

\includesvg{svg-image}

I hope it helps!

Upvotes: 7

Related Questions