【问题标题】:Error generating PDF document with Rmarkdown when output_dir contains spaces当 output_dir 包含空格时,使用 Rmarkdown 生成 PDF 文档时出错
【发布时间】:2019-07-16 16:18:55
【问题描述】:

这是一个名为 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 文件时,它未能在线包含绘图,因为它包含一个空格(在 mwetest 之间)。

\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 模板)。我也尝试修改模板以将其添加到标题中,但无济于事。

如何将 rmarkdown 与 xelatex 一起使用并指定包含空格的输出目录?

是否有一些选项可以强制 pandoc 将图像路径用双引号括起来?

在你建议我重命名路径以删除空间之前,因为它们不属于那里(我完全同意你的观点),这是一个同步文件夹,我无法重命名(感谢 OneDrive)。

【问题讨论】:

标签: r pdf r-markdown


【解决方案1】:

上面的代码似乎确实适用于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"


【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多