Quarto+Shiny自动化报表:如何正确调用独立PDF报告并传参
在Quarto(Flexdashboard)+ Shiny环境中正确调用外部Quarto报告并生成PDF
问题背景
基于Quarto Flexdashboard与Shiny搭建自动化报表系统,支持用户上传数据、通过交互仪表板探索统计信息,最终生成匹配所选统计项的PDF报告。
环境配置
主文件main.qmd为Shiny Flexdashboard结构:
--- title: "Reporting Tool" author: "XY" output: flexdashboard::flex_dashboard runtime: shiny ---
独立Quarto文件src/pdf_file.qmd负责渲染最终PDF报告,需接收仪表板传入的输入参数。
当前报告调用实现
在main.qmd中通过downloadHandler触发报告生成:
output$download_report <- downloadHandler( filename = function() { paste0("microbiome-report-", Sys.Date(), ".pdf") }, content = function(file) { # Ensure correct path resolution quarto_file <- normalizePath("src/pdf_file.qmd", mustWork = TRUE) temp_output_dir <- tempfile() dir.create(temp_output_dir, showWarnings = FALSE) tryCatch({ # Render the Quarto report and specify output directory quarto::quarto_render( input = quarto_file, output_format = "pdf", output_file = "report.pdf", output_dir = temp_output_dir, execute_params = list( physeq = isolate(reactive_phyloseq()), metadata = isolate(uploaded_metadata()), tax_level = isolate(input$tax_level), metadata_group = isolate(input$metadata_group), alpha_indices = isolate(input$alpha_indices) ) ) # Copy the generated file to the correct location for download file.copy(file.path(temp_output_dir, "report.pdf"), file, overwrite = TRUE) }, error = function(e) { print(paste("Error generating Quarto report:", e$message)) }) } )
遇到的问题
- 触发下载时,Quarto无法找到
src/pdf_file.qmd文件 - 单独运行
normalizePath("src/pdf_file.qmd", mustWork = TRUE)能返回正确绝对路径,但在Shiny环境中Quarto仍报错 - 报错信息:
Warning: Error in normalizePath: path[1]="src/pdf_file.qmd": The system cannot find the specified path
已尝试的方案
- 确认
pdf_file.qmd存在于src/目录 - 在
quarto_render()中直接使用绝对路径 - 非Shiny环境下手动运行
quarto::quarto_render("src/pdf_file.qmd")可正常生成报告 - 验证
quarto::quarto_path()配置正确
解决方案
1. 解决路径定位问题:使用here包规避工作目录差异
Shiny运行Quarto Flexdashboard时,工作目录可能并非main.qmd所在的项目根目录,导致相对路径失效。使用here包可以基于项目结构自动定位文件,不受工作目录影响:
首先安装并加载here包:
install.packages("here") library(here)
修改downloadHandler中文件路径的获取逻辑:
# 替换原quarto_file定义 quarto_file <- here("src", "pdf_file.qmd")
2. 确认外部Quarto报告的参数定义
确保pdf_file.qmd的YAML头中已声明所有接收的参数,否则无法正确接收execute_params传递的值:
--- title: "Microbiome Report" output: pdf_document params: physeq: NULL metadata: NULL tax_level: NULL metadata_group: NULL alpha_indices: NULL ---
3. 优化临时文件清理(可选)
在tryCatch中添加finally块,确保临时目录在报告生成完成后被清理,避免残留文件:
tryCatch({ # 原渲染逻辑... }, error = function(e) { print(paste("Error generating Quarto report:", e$message)) }, finally = { # 清理临时目录 unlink(temp_output_dir, recursive = TRUE) })
4. 排查工作目录(可选)
若仍有路径问题,可在downloadHandler中添加代码查看当前工作目录,确认路径差异:
print(paste("Current working directory:", getwd()))
验证方案
修改后重新运行main.qmd,触发下载功能,此时Quarto应能正确找到src/pdf_file.qmd并传递参数生成PDF报告。
内容的提问来源于stack exchange,提问作者user30058700
相关产品推荐
相关产品推荐

