当output_dir包含空格时,使用Rmarkdown生成PDF文档时出错

时间:2019-07-16 16:18:55

标签: r pdf r-markdown

这是一个名为 mwe.Rmd 的最小工作示例:

---
output: 
  pdf_document:
    latex_engine: xelatex
    keep_tex: TRUE
## header-includes:
##     - \usepackage[space]{grffile}
---

```{r}

plot(1, 1)

```

这将在调用rmarkdown::render("~/repos/mwe test/mwe.Rmd")时起作用。但是,如果我致电rmarkdown::render("~/repos/mwe test/mwe.Rmd", output_dir = "~/repos/mwe test/reports/"),它将失败并显示以下错误:

/usr/local/bin/pandoc +RTS -K512m -RTS test_rmarkdown_fail.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output pandoc4f583fe0effa.tex --template /usr/local/lib/R/3.6/site-library/rmarkdown/rmd/latex/default-1.17.0.2.tex --highlight-style tango --pdf-engine xelatex --variable graphics=yes --variable 'geometry:margin=1in' --variable 'compact-title:yes' 
! Missing $ inserted.
<inserted text> 
                $
l.132 ...files/figure-latex/unnamed-chunk-1-1.pdf}

当我检查.tex文件时,由于包含空格(在 mwe test 之间),因此无法包含图形。

\includegraphics{/Users/savey/repos/mwe test/reports/test_rmarkdown_fail_files/figure-latex/unnamed-chunk-1-1.pdf}

未指定output_dir时,这只是相对路径,因此可以正常工作。

latex_engine设置为pdftex而不使用xelatex时,带有空格的路径可以正常工作。我试图将space选项添加到LaTeX软件包grffile中,但是出现一个错误,表明选项冲突(使用默认tex模板)。我也尝试过修改模板以将其添加到标题中,但无济于事。

如何在xelatex中使用rmarkdown并指定包含空格的输出目录?

是否可以强制Pandoc将图像路径用双引号引起来?

在您建议我重命名路径以删除空格(因为它们不属于该空格)(我完全同意)之前,这是一个同步的文件夹,我无法重命名(感谢OneDrive)。 / p>

1 个答案:

答案 0 :(得分:3)

以上代码似乎确实适用于 pdflatex

对于 xelatex,解决方法可能是使用临时目录:

origin <- "./repos/mwe test/mwe.Rmd"
destination <- "./repos/mwe test/reports"

render <- function(origin,destination) {
  tmpdir <- tempdir()
  on.exit(unlink(tmpdir))
  rmarkdown::render(origin, output_dir = tmpdir)
  suppressWarnings(dir.create(destination))
  file.copy(file.path(tmpdir,paste0(basename(tools::file_path_sans_ext(origin)),'.pdf')),destination, overwrite = T)
}

render(origin,destination)

#processing file: mwe.Rmd
#  |...................................                                   |  50%
#  ordinary text without R code
#
#  |......................................................................| 100%
#label: unnamed-chunk-1
#
#output file: mwe.knit.md
#
#/usr/bin/pandoc +RTS -K512m -RTS mwe.utf8.md --to latex --from  markdown+autolink_bare_uris+tex_math_single_backslash --output /tmp/RtmpnHeDOy/mwe.tex --self-contained --highlight-style tango --pdf-engine xelatex --variable graphics --lua-filter /usr/local/lib/R/site-library/rmarkdown/rmd/lua/pagebreak.lua --lua-filter /usr/local/lib/R/site-library/rmarkdown/rmd/lua/latex-div.lua --variable 'geometry:margin=1in'

#Output created: /tmp/RtmpnHeDOy/mwe.pdf
#[1] TRUE

dir("./repos/mwe test/reports")
[1] "mwe.pdf"