Why does Rmd not render to pdf while html is fine

坚强是说给别人听的谎言 提交于 2019-12-23 19:20:04

问题


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...


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/55595569/why-does-rmd-not-render-to-pdf-while-html-is-fine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!