Search code examples
rofficer

Adding image to text box using officer


I am looking at adding an image to a word document using the officer package. The word document template looks like this: enter image description here

These are all text boxes and I am able to replace all the text such as StudentName, Enrollment number etc. but don't know how to add an image to the text box called picture. This is what I have tried:

my_doc <- read_docx('templates/form_101.docx') %>% 
  body_replace_all_text('Coursename', 'NTCC 01') %>% 
  body_replace_all_text('XXX', 'III') %>% 
  body_replace_all_text('FromDate', '26 Oct') %>% 
  body_replace_all_text('ToDate', '02 Nov 20') %>% 
  body_replace_all_text('StudentName', 'Dhiraj Khanna') %>% 
  body_replace_all_text('12345', '51511-W') %>% 
  body_replace_all_text('ABC', 'A') %>% 
  cursor_reach('picture') %>% 
  # cursor_reach('picture') %>% 
  # body_remove()
  # body_bookmark('picture') %>%
  # body_replace_img_at_bkm('picture',
  #                         value = external_img(src = 'data/images/pic1.png', 
  #                                              width = .2, height = .2))
  body_add_img(src = 'data/images/pic1.png', width = .2, height = .2,
               pos = 'on')

print(my_doc, target = 'templates/output.docx')

None of these approaches (including the commented out ones) give me the desired result. So how do I go about inserting an image in the text box picture.

The template is available here


Solution

  • It works when you alter the template. You need to

    1. create a new textfield where you want the image
    2. Put the image within the textfield, using position "in line with text"
    3. Place a bookmark on the image (in my example it is called "picture")

    I have uploaded a correctly altered file here.

    You can then use the function body_replace_img_at_bkm() as follows:

    library(officer)
    library(magrittr)
    
    my_doc <- read_docx('form_101.docx')
    
    my_doc %>%
      body_replace_img_at_bkm("picture",
                              external_img("im02.png", width = .9, height = .9)) %>%
      print("new_form.docx")