来自用户输入的文件路径作为 Shiny App 中的 get_fields 文件输入

时间:2021-02-17 17:19:15

标签: r pdf shiny shinyapps

我正在构建一个将在本地运行的小程序,人们可以在其中上传 csv 和可填充的 pdf,该工具将执行一个循环,该循环将使用来自 csv 的名称填充 pdf 并将它们保存为 png 文件一个 /output 目录。

我在处理 pdf 部分时遇到问题。他们使用 ShinyFiles 导航到 pdf 并获取其路径,但在尝试获取 pdf 字段 (staplr) 时遇到无效路径错误。我认为 get_fields 正在发生这种情况,但我想不出另一种获取 pdf 位置的方法。

警告:path.expand 中的错误:'path' 参数无效 [没有可用的堆栈跟踪]

下面的代码片段。欢迎任何想法!

library(tidyverse)
library(staplr)
library(DT)
library(shinyFiles)
library(pdftools)

ui <- fluidPage(
  titlePanel(p("Award PDF Creation App", style = "color:#3474A7")),
  sidebarLayout(
    sidebarPanel(
      p("Award Creation Tool"),
      
      # Horizontal line ----
      tags$hr(),
      
      fileInput(inputId = "filedata",
                label = "Choose your CSV file",
                accept = c(".csv")),
      
      shinyFilesButton("pdf", "PDF select", "Please select a PDF", multiple = TRUE, viewtype = "detail"),
      tags$p(),
      tags$p('Please choose the fillable PDF for award creation.'),
      tags$hr()
      
    ),
    mainPanel(h3("Review your CSV format before you Create PDFs"),
              DTOutput(outputId = "table"), 
              tableOutput("contents"),
              actionButton("go", "Create PDFs") 
              )
  )
)

server <- shinyServer(function(input, output, session){
  
  volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())
  shinyFileChoose(input, "pdf", roots = volumes, session = session,
                  filetypes = c('', 'pdf'))
  # by setting `allowDirCreate = FALSE` a user will not be able to create a new directory
  
  pdf <- reactive(input$pdf)

  data <- reactive({
    req(input$filedata)
    read.csv(input$filedata$datapath)
  })
  
  pdfpath <- reactive({
    req(input$pdf)
    as.character(parseFilePaths(volumes,pdf())$datapath)
  })
  
  output$table <- renderDT(
    data()
  )
  
  observeEvent(input$go,{
    req(input$filedata)
    req(input$pdf)
    data <- data()
    pdffields <-get_fields(input_filepath = pdfpath, convert_field_names = F)
    
    withProgress(message = 'Making PDFs', value = 0, {
      for(i in 1:nrow(data)){
        pdffields$`Date`$value <- paste(format(data$AWARD_DATE[i], "%B %d, %Y"))
        pdffields$`First Name Last Name`$value <- paste0(data$FIRST_NAME[i], " ", data$LAST_NAME[i])
        filename <- paste0('./output/', Sys.Date(),
                         '_', data$LAST_NAME[i],
                         '_', data$AWARD[i], '.png')
        set_fields(pdf, filename, pdffields)

        bitmap <- pdf_render_page(filename, page = 1, dpi = 300)
        png::writePNG(bitmap, filename)
        
        # Increment the progress bar, and update the detail text.
        incProgress(1/nrow(data), detail = paste("Processing"))
        
        # Pause
        Sys.sleep(0.1)
      }
    })
  })
})

shinyApp(ui = ui, server = server)

0 个答案:

没有答案