问题
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