问题
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.
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.
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!
回答1:
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")
回答2:
You can plot
images from magick
to add them to a document using ReporteRs
. Here's an example:
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")
回答3:
If anyone is wondering about this with the new officer. I needed to insert a pdf into my document. I converted the pdf to a picture. After migrating to officer, i ended up simply using this code from the officer package:
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" )
The other answers worked too, but after i got used to officer this was the most simple way for me. Hope this is of help in the future! :)
来源:https://stackoverflow.com/questions/51172522/inserting-an-image-or-pdf-into-a-word-document-in-r