Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

As far as I know, inserting an image from internet to LaTeX is not possible. You have to download the image first, and then include it locally.

With R bookdown, I do it like this:

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

knitr::include_graphics('cover.jpg')

It works very well for both the gitbook and pdf outputs. But I do not think it is smart. It is necessary for pdf to download the file first, but unnecessary for gitbook output. The image can be included directly to the gitbook output via:

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

Is there any way to switch them when I want both the pdf and gitbook outputs simultaneously? I mean, when I compile the .Rmd file, I would like to get a .pdf file with the image inserted, and a gitbook file with the original image inserted from the web address.

like image 597
pzhao Avatar asked Sep 20 '17 21:09

pzhao


1 Answers

You can check the current output format in knitr::opts_knit$get('rmarkdown.pandoc.to'). If it is 'html', you use the URL of the image, otherwise use the file path, e.g.

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)

Here knitr:::pandoc_to() is an internal wrapper function of knitr::opts_knit$get('rmarkdown.pandoc.to').

like image 167
Yihui Xie Avatar answered Nov 07 '22 15:11

Yihui Xie