Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

pdf - Using image in r markdown report downloaded from Shiny app

I have created a very large shiny app that has a downloadable pdf report. The client has requested their logo in the header of every page of the pdf. I can get a logo on the pdf when the pdf is by itself (not part of the larger shiny app) but pandoc cannot find the image when I try to download the exact same report from within the shiny app. Below is a minimum working example and a list of things I have tried and failed to get to work. smiley.png is in the folder with app.R and can be replaced by any image. smiley.png is a different image from the one I used in the full app, so it has nothing to do with the original image.

Knitting the rmarkdown by itself works perfectly and includes the header. Trying to download from within the shiny app causes the problem.
I've tried:

  • moving the image into a folder called "images" and referencing imagessmiley.png rather than smiley.png. That fails as well with the same error.
  • referencing /srv/shiny-server/AppName/smiley.png when the app was uploaded to shinyapps.io. Failed with unable to find the image (same type of error).
  • using plain ![Logo](smiley.png) syntax rather than the four header lines. Also failed with the same error of unable to find smiley.png
  • <img src="smiley.png" /> with smiley.png in my www folder does not work. I'm knitting a pdf, not an html. pdf knits but does not include an image. It just removes the html.
  • using plain ![Logo](smiley.png) syntax with smiley.png in my www folder does not work. Same error; can't find smiley.png.

My best guess is that when the app runs, it moves around the directories somehow and the .rmd cannot locate the image. So what do I need to reference in order to find the image? Can I put it in a particular folder? I've tried so many different things and done a lot of research, but have had trouble finding a single similar example. I've used the www folder I use for images in the shiny app (not included below), adding new folders, putting the image in the same folder as the .rmd... It's been a very long process of research, trial, and error with no success.

The app:

library(shiny)
ui<-shinyUI(fluidPage(
  titlePanel("Hello Shiny!"),
  sidebarPanel(
    downloadButton('downloadReport',label="Download Report")
              ),
  mainPanel(
      p("Hello")
           )
  ))

server<-shinyServer(function(input, output) {
   output$downloadReport <- downloadHandler(
      filename = function() {
           paste0('Report_.pdf')
                            },
      content = function(file) {
           src <- normalizePath('report.rmd')
           owd <- setwd(tempdir())
           on.exit(setwd(owd))
           file.copy(src, 'report.rmd')
           library(rmarkdown)
           out <- render('report.rmd',pdf_document())
           file.rename(out, file)
                               }
   )
 })

shinyApp(ui, server)#Runs the app

R markdown report.rmd:

---
title: "Test"
date: "Friday, March 04, 2016"
output: pdf_document
header-includes: usepackage{fancyhdr}
---

addtolength{headheight}{1.0cm}
pagestyle{fancyplain}
lhead{includegraphics[height=1.2cm]{smiley.png}}

enewcommand{headrulewidth}{0pt}

```{r, echo=FALSE}
plot(cars)
```
```{r, echo=FALSE}
plot(cars)
```

The error:

  C:/Apps/RStudio/bin/pandoc/pandoc report.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output report.pdf --template C:AppsR-3.1.1library
markdown
mdlatexdefault.tex --highlight-style tango --latex-engine pdflatex --variable geometry:margin=1in  
 pandoc.exe: Error producing PDF from TeX source.  
 ! Package pdftex.def Error: File `smiley.png' not found.  

 See the pdftex.def package documentation for explanation.  
 Type  H <return>  for immediate help.  
 ...                                              

l.88 end{document}  

Warning: running command 'C:/Apps/RStudio/bin/pandoc/pandoc report.utf8.md --to latex --from  markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output report.pdf --template C:AppsR-3.1.1library
markdown
mdlatexdefault.tex --highlight-style tango --latex-engine pdflatex --variable geometry:margin=1in' had status 43  
Error : pandoc document conversion failed with error 43  
In addition: Warning message:  
package ‘shiny’ was built under R version 3.1.3   
Warning: Error in : pandoc document conversion failed with error 43  
Stack trace (innermost first):  
   55: pandoc_convert  
   54: render  
   53: download$func [C:/Data/Documents/Technomic/Testing images/app.R#25]  
    5: <Anonymous>  
    4: do.call  
    3: print.shiny.appobj  
    2: print  
    1: source  

Thank you! I hope someone has some ideas. I've been researching and trying things for days on and off.

Edit: Fixed the output formatting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Finally found the issue- it wasn't in the rmarkdown at all. I was copying the report.pdf to a temporary directory to be sure I could write to it, which meant the report could no longer find the image. All I had to do was copy the image to the temporary directory as well. Added two new lines, and it now works perfectly!

Hopefully this will help someone else! I know I spent a long time looking for this solution and couldn't find anyone else trying to include an image in a downloadable report.

library(shiny)

# Define UI for application that draws a histogram
ui<-shinyUI(fluidPage(
  titlePanel("Hello Shiny!"),
    sidebarPanel(
      downloadButton('downloadReport',label="Download Report")
    ),
    mainPanel(
      p("Hello")
    )
))

server<-shinyServer(function(input, output) {
  output$downloadReport <- downloadHandler(
    filename = function() {
      paste0('Report_.pdf')
    },
    content = function(file) {
      src <- normalizePath('report.rmd')
      src2 <- normalizePath('smiley.png') #NEW 
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, 'report.rmd')
      file.copy(src2, 'smiley.png') #NEW
      library(rmarkdown)
      out <- render('report.rmd',pdf_document())
      file.rename(out, file)
    }
  )
})

shinyApp(ui, server)#Runs the app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...