通过Shiny将图片上传到knitr文档

An *_*ist 8 r knitr shiny

我正在使用Shiny和knitr的组合来创建PDF文档.

目前我想添加一项功能,允许用户上传将放置在创建文档中的图片.但是,我真的被卡住了,因为我无法获得输入图片的路径.有人可以帮我吗?

简单的例子:

应用:

library(knitr)
library(shiny)

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
      fileInput("picture", label = 'Picture'),
      downloadButton('report', label = 'Download PDF')
      ),

    mainPanel()
  )
)

server <- function(input,output){

  picture <-  reactive({
    input$picture[,4]
  })

  output$report = downloadHandler(
    filename = "test.pdf",

    content = function(file){
      picture = picture()

    out = knit2pdf(input = 'test.Rnw', compiler = 'xelatex', clean = TRUE)
    file.rename(out, file) 
    },

    contentType = 'application/pdf'
  )
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

.Rnw文件:

\documentclass{article}

\begin{document}

Put picture here:
<<echo = FALSE , message = F, results='asis'>>=
cat(paste('\\includegraphics[height=3in]{', picture,'}'))
@

\end{document}
Run Code Online (Sandbox Code Playgroud)

部分'\includegraphics[height=3in]{', picture,'}显然是造成问题,因为我不知道图片路径只是暂时的.

Yih*_*Xie 2

你说你正在使用Shiny Server,那么你应该可以使用图片的完整路径,即使它位于临时目录中(因为目前Shiny Server仅适用于Linux,而LaTeX应该可以使用Linux文件路径,例如/tmp/...../yourfile.png)。问题可能是datapath(ie input$picture[, 4]) 没有文件扩展名,因此 LaTeX 无法识别它。您可以尝试检索原始文件的文件扩展名,并将上传的图片复制到具有相同扩展名的临时文件中,例如

picture <- reactive({
  path1 <- input$picture$datapath
  path2 <- tempfile(fileext = gsub('^(.*)([.].+)$', '\\2', input$picture$name))
  file.copy(path1, path2, overwrite = TRUE)
  path2
})
Run Code Online (Sandbox Code Playgroud)