将图像或pdf插入R中的word文档

Inserting an image or pdf into a word document in R

我正在使用一个循环创建许多表格等,并使用 ReporteRs 包将其导出到 word 文档中。因此,例如,我有一个包含许多页不同图形、表格和文本的 word 文档。

我想通过循环将图像(或 pdf - 两者都可以)插入其中(因为循环会生成许多不同的 word 文档)。我已经下载了 ImageMagick 和 magick 包来处理图像。现在我在 R 中有了我的图像,但我不知道如何将它添加到我的文档中。

我知道 ReporteRs 有一个插入外部图像的 addImage 命令(老实说,我很难弄清楚那个)。是否可以将内部 images/pdf 添加到文档中?

希望大家多多指教。先感谢您!

您可以 plot 来自 magick 的图像,然后使用 ReporteRs 将它们添加到文档中。这是一个例子:

library(ReporteRs)
library(magick)

sample.doc <- docx(title="Sample")

## add original Frink
sample.image <- image_read("https://jeroen.github.io/images/frink.png")
sample.doc <- addPlot(sample.doc,
                      fun=plot,
                      x=sample.image)

## add rotated Frink
sample.doc <- addPlot(sample.doc,
                      fun=function(x) plot(image_rotate(x, 45)),
                      x=sample.image)


## save the document to disk
writeDoc(sample.doc, "sample.docx")

我强烈建议将您的代码迁移到 officer,因为 ReporteRs 将于 2018 年 7 月 16 日从 CRAN 中删除。从@d125q 写的代码来看,这将被转换为:

library(officer)
library(magick)

download.file("https://jeroen.github.io/images/frink.png", "frink.png")
dims1 <- attributes(png::readPNG("frink.png"))$dim/72
sample.image <- image_read("frink.png")
image_write(image_rotate(sample.image, 45), "frink_rotated.png")
dims2 <- attributes(png::readPNG("frink_rotated.png"))$dim/72


sample.doc <- read_docx()
sample.doc <- body_add_img(sample.doc, src = "frink.png", width = dims1[2], height = dims1[1] )
sample.doc <- body_add_img(sample.doc, src = "frink_rotated.png", width = dims2[2], height = dims2[1] )
print(sample.doc, target = "sample.docx")

如果有人想知道新官员的这个问题。我需要在我的文档中插入 pdf。我把pdf转成了图片。迁移到 officer 之后,我最终只使用了 officer 包中的代码:

img.file <- file.path( R.home("doc201"), "P:/path to my picture", "name.png" )

doc201 <- body_add_img(x = doc201, src = "P:/path/name.png", height = 10, width = 6, pos = "after" )

其他答案也有效,但在我习惯了 officer 之后,这对我来说是最简单的方法。希望这对将来有帮助! :)