Search code examples
rofficer

Logo and text on same line Officer R


I need to place a logo on my document and have a text on the same line.


library(officer)
library(magrittr)

my_doc <- read_docx()

my_doc <- my_doc %>%
  body_add_fpar(fpar(ftext(
    paste0("Text"),
    fp_text( font.size = 16)),
    fp_p = fp_par(text.align = "right",shading.color = '#E8E8E8')), pos = 'on') 

my_doc <- my_doc %>%
  body_add_img('logo.png', width = 3, height = 0.9, pos = 'after')

my_doc <- my_doc %>%
  body_add_fpar(fpar(ftext(
    paste0("Text"),
    fp_text( font.size = 16)),
    fp_p = fp_par(text.align = "right",shading.color = '#E8E8E8')), pos = 'after') 
my_doc <- my_doc %>%
  body_add_fpar(fpar(ftext(
    paste0("Text"),
    fp_text( font.size = 16)),
    fp_p = fp_par(text.align = "right",shading.color = '#E8E8E8')), pos = 'after') 
my_doc <- my_doc %>%
  body_add_fpar(fpar(ftext(
    paste0("Text"),
    fp_text( font.size = 16)),
    fp_p = fp_par(text.align = "right",shading.color = '#E8E8E8')), pos = 'after') 

print(my_doc, target = 'file.docx')

Current result is:

enter image description here

Desired result is:

enter image description here

I tried to manipulate the position, tried to create some sort of 2 column layout. No success...


Solution

  • Here is a solution with a 2 columns section:

    library(officer)
    library(magrittr)
    
    img.file <- file.path( R.home("doc"), "html", "logo.jpg" )
    
    a_par <- fpar(
      external_img(src = img.file, height = 1.06/2, width = 1.39/2),
      fp_p = fp_par(text.align = "center", padding = 5))
    
    b_par <- fpar(
      run_columnbreak(),
      "Text",
      run_linebreak(),
      "Text",
      run_linebreak(),
      "Text",
      run_linebreak(),
      "Text",
      run_linebreak(),
      "Text",
      run_linebreak(),
      fp_p = fp_par(text.align = "center", padding = 5))
    
    doc_1 <- read_docx()
    
    page_size <- docx_dim(doc_1)$page
    
    bs <- block_section(prop_section(
      section_columns = section_columns(widths = c(3, 1), space = .1, sep = FALSE),
      page_size = page_size(width = page_size["width"], height = page_size["height"]),
      type = "continuous"))
    
    doc_1 <- body_add_fpar(doc_1, value = a_par)
    doc_1 <- body_add_fpar(doc_1, value = b_par)
    doc_1 <- body_end_block_section(doc_1, bs)
    doc_1 <- body_add_par(doc_1, value = "a new section", style = "Normal")
    
    print(doc_1, target = tempfile(fileext = ".docx")) 
    

    enter image description here