【后续简化问题】Shiny调用Rmarkdown生成PDF时页眉logo.png文件找不到的错误求助
Fix "logo.png not found" Error When Rendering RMarkdown PDF from Shiny App
你遇到的问题很典型:单独编译report.Rmd时能正常显示页眉的logo,但通过Shiny调用rmarkdown::render()生成PDF时,却提示找不到logo.png。这背后的原因其实很好理解:
当你单独运行RMarkdown时,LaTeX是在当前工作目录下查找logo.png的;而Shiny会把report.Rmd复制到系统的临时目录(tempdir())里去渲染,但没有把logo.png同步过去,所以LaTeX在临时目录里找不到这个图片文件,就抛出了错误。
下面给你两种简单有效的解决方案:
方案1:把logo复制到临时目录(推荐)
在Shiny的downloadHandler函数里,复制report.Rmd之后,再把logo.png也复制到临时目录。这样渲染时LaTeX就能在同一个目录下找到图片了。
修改后的app.R代码如下(重点看新增的那一行):
app.R # Global variables can go here n <- 200 # Define the UI ui <- bootstrapPage( numericInput('n', 'Number of obs', n), plotOutput('plot'), downloadButton('report', 'Generate Report') ) # Define the server code server <- function(input, output) { output$plot <- renderPlot({ hist(runif(input$n)) }) # create markdown report ---------------------------------- output$report <- downloadHandler( filename = "report.pdf", content = function(file) { tempReport <- file.path(tempdir(), "report.Rmd") file.copy("report.Rmd", tempReport, overwrite = TRUE) # 新增:把logo.png复制到临时目录 file.copy("logo.png", tempdir(), overwrite = TRUE) params <- list(scores = runif(input$n)) # 修正:之前传的是input$n(单个数字),这里改成数值向量适配hist需求 rmarkdown::render(tempReport, output_file = file, params = params, envir = new.env(parent = globalenv()) ) } ) } # Return a Shiny app object shinyApp(ui = ui, server = server)
方案2:在Rmd中使用绝对路径指定logo
如果你不想复制文件,可以直接在report.Rmd里写logo.png的绝对路径,比如:
\rhead{\includegraphics[width = .05\textwidth]{/Users/yourname/your-project-folder/logo.png}}
不过这种方法不够灵活,一旦文件位置变动就需要修改路径,所以更推荐方案1。
完成修改后,重新运行Shiny app,点击「Generate Report」按钮,就能生成带有logo页眉的PDF了。
内容的提问来源于stack exchange,提问作者TarJae
相关产品推荐
相关产品推荐

