2

Is it possible to keep the original aspect ration while inserting an image in a .docx document with the function body_replace_img_at_bkm() from the package officer?

my code looks like this:

library(officer)
library(magrittr)

img.file <- file.path( R.home("doc"), "html", "logo.jpg" )

doc <- read_docx() %>% 
  body_add_par("centered text", style = "centered") %>%
  slip_in_text(". How are you", style = "strong") %>%
  body_bookmark("text_to_replace") %>%
  body_replace_img_at_bkm("text_to_replace", value = external_img(src = img.file, width = .03, height = .03)) %>%
  print(target = "yourpath/KeepAspectRatio.docx")  

I tried this:

...
body_replace_img_at_bkm("text_to_replace", value = external_img(src = img.file)) %>%
...

This did not work. It shows the image with (i believe) the correct aspect ration but the image is not the desired size. I want to make it smaller without changing the aspect ratio.

Thank you very much in advance

p.s. I had to use width = .03, height = .03 in my case because the image was huge for some reason.

1 Answers1

2

For png files I found the following solution/alternative:

library(png)

ImgZoom <- 3

temp <- readPNG("filepath.png",native = TRUE,info = TRUE)

body_replace_img_at_bkm("text_to_replace",
                        value = external_img(src = img.file
                                             ,width = ImgZoom*(attr(temp,"info")$dim[1]/attr(temp,"info")$dim[2])
                                             ,height = ImgZoom*(attr(temp,"info")$dim[2]/attr(temp,"info")$dim[2])))

But this is a small detour and does only work for png files so far. I will also try this for other file types.

The best way would be an extra option in the function: body_replace_img_at_bkm().

Something like: body_replace_img_at_bkm(...,keep_aspect_ratio = TRUE)