2

I am running into a problem when trying to include a web-based image within a R Markdown PDF document.

Minimal Example:

---
title: "Random"
output: pdf_document
---

![Benjamin Bannekat](https://octodex.github.com/images/bannekat.png)

Knitting the above results in the error:

! Package pdftex.def Error: File `https://octodex.github.com/images/bannekat.pn g' not found.

However, if I use the following code, the image shows up:

---
title: "Random"
output:
  html_document: default
  html_notebook: default
---

![Benjamin Bannekat](https://octodex.github.com/images/bannekat.png)

The same code works fine when output is HTML.

How can I make the image show up in a PDF document?

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
Adrian
  • 9,229
  • 24
  • 74
  • 132
  • Hope the answer helps. Just checking: why are you specifying the image path within a code chunk them wrapping it in `cat()`? You could just display the code outside as I have edited the question to do. I would still recommend the use of `include_graphics` as per my answer though. – Michael Harper Aug 01 '18 at 16:32

1 Answers1

3

If you are knitting to PDF, the file has to run through LaTeX. LaTeX has no built-in capacity to display files hosted on the web, as highlighted in this question.

The best workaround for this is to download the web image to your local directory, and then specify this as a file path.

The following code downloads the image using the download.file function, and then displays in using include_graphics. The benefit of include graphics is that it allows you to specify the width of the image in the output document, which I set to 40 pixels.

---
title: "Random"
output: pdf_document
---


```{r results = 'asis', out.width="40px"}
download.file(url = "https://octodex.github.com/images/bannekat.png",
          destfile = "image.png",
          mode = 'wb')
knitr::include_graphics(path = "image.png")
```

enter image description here

Find out more reasons why include_graphics should be used to include graphics in R Markdown documents. Check out my other answer here for more details why.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84