rofficerofficedown

Combine multiple docx with columns in officer R


I am trying to use the officer package in R to create multiple outputs with columns and then combine the outputs into a single document. I am able to create the initial outputs with columns, but when I combine them with body_add_docx() the column formatting goes away. Wondering if I am missing something with my implementation.

# sample text
str1 <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
str1 <- rep(str1, 20)
str1 <- paste(str1, collapse = " ")

# Create initial section with columns
x <- read_docx()
x <- body_add_par(x, str1, style = "Normal") %>% 
  body_end_section_columns(widths = c(3, 3), space = 0, sep = FALSE)

print(x, target = "tmp1.docx")

# Create another output with columns
x <- read_docx()
x <- body_add_par(x, str1, style = "Normal") %>% 
  body_end_section_columns(widths = c(3, 3), space = 0, sep = FALSE)

print(x, target = "tmp2.docx")

# Combine the rendered sections together
read_docx(path = "tmp1.docx") %>% 
  body_add_break() %>% 
  body_add_docx(src = "tmp2.docx") %>% 
  print(target = "final.docx")

The final output does not have the same column structure as the inputs.


Solution

  • A thread is already available here: https://github.com/davidgohel/officer/issues/431

    Word does not keep the sections of the embedded documents as is. officer just adds it and does not change the file. It seems to me it is not possible to add a docx into another docx and preserve the original sections, they must be defined in the target/final document as when you use Word MANUALLY.

    The section should be added/configured in the final/main document:

    library(officer)
    
    file1 <- "file1.docx"
    file2 <- "file2.docx"
    file3 <- "file3.docx"
    
    x <- read_docx()
    x <- body_add_par(x, "hello world 1", style = "Normal")
    print(x, target = file1)
    
    x <- read_docx()
    x <- body_add_par(x, "hello world 2", style = "Normal")
    print(x, target = file2)
    
    ## First portrait, then landscape
    psportrait <- prop_section(
      page_size = page_size(orient = "portrait")
    )
    pslandscape <- prop_section(
      page_size = page_size(orient = "landscape")
    )
    
    # solution 1: keep default section as portrait
    x <- read_docx(path = file1)
    
    x <- body_end_block_section(x, value = block_section(pslandscape))
    
    x <- body_add_docx(x, src = file2)
    
    x <- body_end_block_section(x, value = block_section(psportrait))
    
    print(x, target = file3)