Search code examples
svglatexbookdown

How to make a PDF using bookdown including SVG images


I have some R markdown that includes the following code:

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

When using bookdown to produce HTML output everything works as expected.

When using bookdown to produce PDF output I get an error saying ! LaTeX Error: Unknown graphics extension: .svg.

This is understandable as knitr uses Latex's \includegraphics{images/Huff-2009-fig5.1.svg} to include the image. So, it's not a bug per se.

Is there a better way to include the SVG image so I don't need to pre-process it into, say, a PDF or PNG?


Solution

  • You can create a helper function to convert SVG to PDF. For example, if you have the system package rsvg-convert installed, you may use this function to include SVG graphics:

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

    You may also consider R packages like magick (which is based on ImageMagick) to convert SVG to PDF.