如何以智能方式将互联网上的图像插入到 R bookdown 生成的 pdf 文件中?

How can I insert an image from internet to the pdf file produced by R bookdown in a smart way?

据我所知,从互联网上插入图像到 LaTeX 是不可能的。您必须先下载图像,然后将其包含在本地。

对于 R bookdown,我是这样做的:

download.file('https://bookdown.org/yihui/bookdown/images/cover.jpg','cover.jpg', mode = 'wb')

knitr::include_graphics('cover.jpg')

它适用于 gitbook 和 pdf 输出。但我认为这并不聪明。 pdf需要先下载文件,gitbook输出则不需要。图像可以通过以下方式直接包含到 gitbook 输出中:

knitr::include_graphics('https://bookdown.org/yihui/bookdown/images/cover.jpg')

当我同时想要 pdf 和 gitbook 输出时,有什么办法可以切换它们吗?我的意思是,当我编译 .Rmd 文件时,我想得到一个插入了图像的 .pdf 文件,以及一个从网址插入原始图像的 gitbook 文件。

您可以在knitr::opts_knit$get('rmarkdown.pandoc.to')中查看当前的输出格式。如果是'html',则使用图像的URL,否则使用文件路径,例如

cover_url = 'https://bookdown.org/yihui/bookdown/images/cover.jpg'
if (!file.exists(cover_file <- 'cover.jpg'))
  download.file(cover_url, cover_file, mode = 'wb')
knitr::include_graphics(if (identical(knitr:::pandoc_to(), 'html')) cover_url else cover_file)

这里knitr:::pandoc_to()knitr::opts_knit$get('rmarkdown.pandoc.to')的内部包装函数。