Search code examples
rfor-loopimagemagickreporters

Inserting an image or pdf into a word document in R


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!


Solution

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