如何通过编程在Quarto输出的Word文档中嵌入源文件?
编程实现Quarto/Rmd生成Word时嵌入源文件
完全可以通过编程实现,不需要手动操作,Quarto(.qmd)和R Markdown(.Rmd)文件都支持这个需求。核心思路是利用knitr的后处理钩子,结合officer包在Word生成完成后自动嵌入源文件。
具体步骤:
安装所需R包:
install.packages(c("officer", "here"))(
here用于更稳健地定位文件路径,避免依赖特定编辑器环境)在你的源文件(
create_word.qmd或.Rmd)中添加以下代码块(建议放在文档末尾):knitr::knit_hooks$set(post.process = function(x, options) { # 判断输出格式是否为Word if (grepl("docx", options$output_format)) { library(officer) library(here) # 读取生成的Word文档 doc <- read_docx(x) # 定位源文件路径 source_file <- here(basename(rstudioapi::getSourceEditorContext()$path)) # 若未使用RStudio,可直接手动指定路径:source_file <- here("create_word.qmd") # 在Word文档末尾添加说明并嵌入源文件 doc <- doc %>% body_add_par("嵌入的文档源文件:", style = "Heading 2") %>% body_add_attachment(src = source_file) # 覆盖原输出的Word文件 print(doc, target = x) } return(x) })正常渲染文件:
- Quarto:点击渲染按钮或运行
quarto::quarto_render("create_word.qmd", output_file = "output_word_file.docx") - Rmd:点击渲染按钮或运行
rmarkdown::render("create_word.Rmd", output_file = "output_word_file.docx")
- Quarto:点击渲染按钮或运行
渲染完成后,打开生成的output_word_file.docx,就能在文档末尾找到嵌入的源文件副本,无需手动操作。
内容的提问来源于stack exchange,提问作者Scott White
相关产品推荐
相关产品推荐

