在Shiny应用中用rmarkdown导出HTML/PDF时遇tools::file_path_as_absolute错误
一、解决Shiny导出时tools::file_path_as_absolute文件不存在错误
你遇到的Error in tools::file_path_as_absolute: file '/tmp/RtmpCjHU3c/report.Rmd' does not exist错误,核心原因是file.copy("report.Rmd", tempReport, overwrite = TRUE)这一步没成功复制文件——Shiny应用运行时的工作目录可能和你存放report.Rmd的目录不一致,导致找不到原文件。这里有几个可靠的解决方案:
1. 确认并使用report.Rmd的绝对路径
先找到report.Rmd的实际路径,如果它和Shiny脚本在同一个文件夹里,可以用normalizePath()获取绝对路径,确保复制操作能找到源文件:
ui <- fluidPage( sliderInput("slider", "Slider", 1, 100, 50), downloadButton("report", "Generate report") ) server <- function(input,output) { output$report <- downloadHandler( filename = "report.html", content = function(file) { # 获取report.Rmd的绝对路径,mustWork=TRUE会强制检查文件是否存在 original_report <- normalizePath("report.Rmd", mustWork = TRUE) tempReport <- file.path(tempdir(), "report.Rmd") file.copy(original_report, tempReport, overwrite = TRUE) params <- list(n = input$slider) rmarkdown::render(tempReport, output_file = file, params = params, envir = new.env(parent = globalenv()) ) }) } shinyApp(ui = ui, server = server)
如果还是提示找不到文件,可以在Shiny脚本开头加print(getwd()),看看当前工作目录是什么,把report.Rmd移到这个目录下,或者直接修改original_report的路径到文件实际位置。
2. 把report.Rmd放在Shiny的资源目录
如果你的Shiny应用是包结构,或者想规范管理资源,可以把report.Rmd放在www文件夹里,通过资源路径访问:
# 在server函数外设置资源路径,指向www下的reports子文件夹 shiny::addResourcePath("reports", "./www/reports") server <- function(input, output) { output$report <- downloadHandler( filename = "report.html", content = function(file) { original_report <- shiny::resourcePath("reports/report.Rmd") tempReport <- file.path(tempdir(), "report.Rmd") file.copy(original_report, tempReport, overwrite = TRUE) # 后续render代码保持不变 } ) }
二、解决TinyTeX安装冲突问题
你提到系统已安装TeX Live,强制安装TinyTeX时出现路径错误,这里分两种场景处理:
1. 保留系统TeX Live,无需安装TinyTeX
既然你说标准rmarkdown文档用TeX Live可以正常生成PDF,那其实没必要强制安装TinyTeX——先解决上面Shiny的文件路径问题,大概率就能正常导出PDF/HTML了。
2. 卸载系统TeX Live后安装TinyTeX
如果确实需要使用TinyTeX,建议先彻底卸载系统的TeX Live,避免路径冲突:
在Ubuntu终端运行以下命令:
# 卸载所有TeX Live相关包 sudo apt remove --purge texlive* # 清理残留依赖和配置文件 sudo apt autoremove sudo apt clean
卸载完成后重启R/RStudio,再运行:
tinytex::install_tinytex()
这样就能正常完成TinyTeX的安装了。
3. 不卸载系统TeX Live,调整PATH优先级
如果不想卸载系统TeX Live,可以通过调整环境变量让TinyTeX的tlmgr优先被调用:
- 手动下载对应Linux版本的TinyTeX压缩包,解压到
~/.TinyTeX目录 - 打开
~/.bashrc文件,添加以下内容:
export PATH="$HOME/.TinyTeX/bin/x86_64-linux:$PATH"
- 运行
source ~/.bashrc使配置生效 - 在R中运行
Sys.which("tlmgr"),确认输出指向~/.TinyTeX/bin/x86_64-linux/tlmgr - 最后运行
tinytex::install_tinytex(force = TRUE)完成配置覆盖
内容的提问来源于stack exchange,提问作者bankhedge12

