Christoph
Christoph

Reputation: 7063

Why does Rmd not render to pdf while html is fine

If I render the following file to html, everything works. If I render to pdf, it throws the error

output file: test.knit.md ! LaTeX Error: Unknown graphics extension: .png?raw=true. Fehler: Failed to compile test.tex. See test.log for more info.

The reason is, that the Rmd is translated to

\begin{figure}
\centering
\includegraphics[width=4.16667in]{pics/myimage.png?raw=true}
\caption{Some text here.}
\end{figure}

in test.tex and above code does not make sense of course.
Example:

---
title: "Untitled"
author: "Myname"
date: "5 April 2019"
output:
  pdf_document:
    number_sections: yes
    toc: yes
    toc_depth: '2'
  html_document:
    keep_md: yes
    number_sections: yes
    toc: yes
    toc_depth: 2
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

text

![Some text here.](pics/myimage.png?raw=true){width=400px}

text

I need the ?raw=TRUE for github, see here. You can also clone the example from here!

Edit: I also asked the developers here, because I have the feeling, something goes wrong with keep_md: yes...

Upvotes: 3

Views: 741

Answers (2)

Yihui Xie
Yihui Xie

Reputation: 30194

You can condition the image path on the output format via knitr::is_html_output(), e.g.,

---
title: "Untitled"
author: "Myname"
date: "5 April 2019"
output:
  html_document:
    keep_md: yes
    number_sections: yes
    toc: yes
    toc_depth: 2
    self_contained: false
  pdf_document:
    number_sections: yes
    toc: yes
    toc_depth: '2'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

text

```{r, echo=FALSE, results='asis'}
cat(
  '![Some text here.](pics/myimage.png',
  if (knitr::is_html_output()) '?raw=true',
  '){width=400px}',
  sep = ''
)
```

text

Upvotes: 2

symbolrush
symbolrush

Reputation: 7467

I would use the following workaround:

  1. In your .rmd remove the part ?raw=true.
  2. After knitting to html: Read the html file into R, replace .png with .png?raw=true and store it again:

You can use the following code:

html <- readLines("your-file.html")
html <- sapply(html, function(x) gsub(".png", ".png?raw=true", x))
writeLines(html, "your-file.html")

Like that you have the ?raw=true annotation in your html file (where they belong) and not in the .tex file (and the .pdf) where they don't have a meaning.

Upvotes: 1

Related Questions