Knit word document from Shiny App with template.docx

落爺英雄遲暮 提交于 2020-08-26 10:01:15

问题


I'm trying to knit a word document from a shiny app using a template.docx file. I get the following error message:

pandoc.exe: template.docx: openBinaryFile: does not exist (No such file or directory)

The following 3 files were all currently located in the same directory.

app.R:

library(shiny)
library(rmarkdown)

ui <- fluidPage(

    titlePanel("Word template"),

    sidebarLayout(
        sidebarPanel(),

        mainPanel(
            downloadButton("download", "Download Report")
        )
    )
)

server <- function(input, output) {

    output$download <- downloadHandler(
        
        filename = function() {
            "report.docx"
        },
        content = function(file) {
            
            src <- normalizePath('report.Rmd')
            
            owd <- setwd(tempdir())
            on.exit(setwd(owd))
            file.copy(src, 'report.Rmd', overwrite = TRUE)
            
            out <- render('report.Rmd',
                          envir = new.env(parent = globalenv()))
            
            file.rename(out, file)
        }
        
    )
    
}

shinyApp(ui = ui, server = server)

report.Rmd:

---
title: "Test"
output:
  word_document:
    reference_docx: template.docx
    
---

`r getwd()`

```{r}
mtcars

```

template.docx is an empty "new" Word 2016 document


回答1:


In the downloadHandler() function you need to copy both .Rmd and .docx files to the temporary directory

content = function(file) {
            
            src <- normalizePath(c('report.Rmd', 'template.docx')) # SEE HERE
            
            owd <- setwd(tempdir())
            on.exit(setwd(owd))
            file.copy(src, c('report.Rmd', 'template.docx'), overwrite = TRUE) # SEE HERE
            
            out <- render('report.Rmd',
                          envir = new.env(parent = globalenv()))
            
            file.rename(out, file)
        }

Thoughts

I wouldn't have worked this out without preparing a reproducible example and thinking about how to describe the problem. It's worth thinking about how to ask your question!



来源:https://stackoverflow.com/questions/62548501/knit-word-document-from-shiny-app-with-template-docx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!