使用rmarkdown::render导出PDF至指定目录时LaTeX编译失败求助
Rmd添加自定义knit函数后LaTeX编译失败的解决办法
问题场景
在Rmd文件的YAML头部添加自定义knit函数指定PDF输出路径后,LaTeX编译失败,仅生成.tex文件但进程终止;移除该函数则可正常生成PDF。
相关YAML配置
--- title: "LHD_generation" author: "hcghkgvjv" date: "`r format(Sys.time(), '%d %B, %Y')`" output: pdf_document: toc: yes toc_depth: 3 html_notebook: toc: yes toc_depth: 3 toc_float: yes html_document: theme: simplex highlight: kate fig_caption: yes fig_height: 4 fig_width: 6 toc: yes toc_float: yes toc_depth: 3 # word_document: # toc: yes # toc_depth: 3 knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, output_file = paste0(dirname(inputFile), "/../Results", '/LHD_generation.pdf'), output_format = "pdf_document")}) ---
错误信息
output file: LHD_generation.knit.md /Applications/RStudio.app/Contents/MacOS/quarto/bin/tools/pandoc +RTS -K512m -RTS LHD_generation.knit.md --to latex --from markdown+autolink_bare_uris+tex_math_single_backslash --output pandocd714116efe8f.tex --lua-filter /Users/massisenergy/Library/R/x86_64/4.2/library/rmarkdown/rmarkdown/lua/pagebreak.lua --lua-filter /Users/massisenergy/Library/R/x86_64/4.2/library/rmarkdown/rmarkdown/lua/latex-div.lua --embed-resources --standalone --table-of-contents --toc-depth 3 --highlight-style tango --pdf-engine pdflatex --variable graphics --variable 'geometry:margin=1in' Error: LaTeX failed to compile /Users/massisenergy/Library/Mobile Documents/com~apple~CloudDocs/Sync/inSilicoE3DBP_model_MRE/Analysis/../Results/LHD_generation.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. Execution halted
解决办法
确保输出目录存在
自定义路径中的../Results相对目录可能未创建,需提前手动生成,或在knit函数中添加自动创建逻辑:knit: (function(inputFile, encoding) { out_dir <- file.path(dirname(inputFile), "../Results") if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE) rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(out_dir, 'LHD_generation.pdf'), output_format = "pdf_document")})显式继承PDF输出配置
自定义render调用不会自动继承YAML中pdf_document的配置(如目录设置),需显式传递参数:knit: (function(inputFile, encoding) { out_dir <- file.path(dirname(inputFile), "../Results") if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE) rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(out_dir, 'LHD_generation.pdf'), output_format = rmarkdown::pdf_document( toc = TRUE, toc_depth = 3 ))})排查LaTeX依赖缺失
手动用pdflatex编译生成的.tex文件,查看具体错误提示(如缺失宏包),再用TinyTeX安装对应依赖:tinytex::tlmgr_install("缺失的宏包名称")规避云同步目录干扰
当前文件存放在iCloud同步目录,云同步可能锁定编译中的文件,建议将项目移至本地非同步目录测试。
内容的提问来源于stack exchange,提问作者massisenergy
相关产品推荐
相关产品推荐

