在R中的Word文档中插入图像或pdf

问题描述:

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

Im working with a loop that creates many tables etc. and exports it into word documents with ReporteRs package. So for example I then have a word document with many pages of different graphs, tables and text.

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

I want to insert an image (or pdf - either is fine) into it through the loop (since the loop produces many different word documents). I have downloaded the ImageMagick and magick packages to work with the images. Now I have my image in R, but I cant figure out how to add it to my document.

我知道ReporteRs有一个addImage命令,该命令可以插入外部图像(很抱歉,我难以确定该图像).是否可以在文档中添加内部图像/pdf?

I know that ReporteRs has an addImage command that inserts external images (honestly im having trouble figuring that one out to). Is it possible adding internal images/pdf's to a document?

希望你们能给我一些提示.先感谢您!

Hope you guys can gives me some tips. Thank you in advance!

我强烈建议您将代码迁移到officer,因为ReporteRs将于2018-07-16从CRAN中删除.从@ d125q编写的代码中,将其转换为:

I strongly recommand to migrate your code to officer as ReporteRs will be removed from CRAN on 2018-07-16. From the code @d125q wrote, this would be transformed as :

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")