【问题标题】:How to make a PDF using bookdown including SVG images如何使用包含 SVG 图像的 bookdown 制作 PDF
【发布时间】:2018-05-04 00:12:30
【问题描述】:

我有一些包含以下代码的 R 降价:

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

当使用 bookdown 生成 HTML 输出时,一切正常。

当使用 bookdown 生成 PDF 输出时,我收到一条错误消息 ! LaTeX Error: Unknown graphics extension: .svg.

这是可以理解的,因为 knitr 使用 Latex 的 \includegraphics{images/Huff-2009-fig5.1.svg} 来包含图像。所以,它本身并不是一个错误。

有没有更好的方法来包含 SVG 图像,这样我就不需要将其预处理为 PDF 或 PNG?

【问题讨论】:

    标签: svg latex bookdown


    【解决方案1】:

    您可以创建一个辅助函数来将 SVG 转换为 PDF。例如,如果你安装了系统包rsvg-convert,你可以使用这个函数来包含S​​VG图形:

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

    您也可以考虑使用 R 包,如 ma​​gick(基于 ImageMagick)将 SVG 转换为 PDF。

    【讨论】:

    • 为了避免每次都转换文件,我将 rsvg-convert 从 R 代码中取出并放入 Makefile,然后通过 RMarkdown 中的 bash 块调用它。 Make 只有在 svgs 自上次构建 pdfs 后发生更改时才会重新构建,因此这是加快编织执行时间的好方法。
    【解决方案2】:

    对于bookdown,我真的不喜欢在我的网站上放置 PDF 文件。所以我使用这个代码:

    if (knitr::is_html_output()) {
      structure("images/01-02.svg", class = c("knit_image_paths", "knit_asis"))
    } else {
      # do something for PDF, e.g. an actual PDF file if you have one,
      # or even use Yihui's code in the other answer
      knitr::include_graphics("images/01-02.pdf")
    }
    

    它将 SVG 文件用于网站(即 HTML 输出)。

    它非常适合生成所有内容:网站、gitbook、pdfbook 和 epub。

    为防止将此代码添加到您的 bookdown 项目中的每个块中,请将其添加到 index.Rmd

    insert_graphic <- function(path, ...) {
      if (knitr::is_html_output() && grepl("[.]svg$", basename(path), ignore.case = TRUE)) {
        structure(path, class = c("knit_image_paths", "knit_asis"))
      } else {
        knitr::include_graphics(path, ...)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      相关资源
      最近更新 更多