1

I only have one "heading 1" and yet it's at the bottom acting like it's the second header. Is there something I'm not aware of?

enter image description here

Code with example data:

library(flextable)
library(dplyr)
library(officer)
library(officedown)

df <- data.frame(text_level = c(1, 4, 2, 4, 3, 4),
                 text_style = c("heading 1", "Normal", "heading 2", "Normal", "heading 3", "Normal"),
                 text_value = c("Section 1", "Lorem ipsum.", "Section 1.1", "Lorem ipsum.", "Section 1.1.1", "Lorem ipsum."))

doc <- read_docx()
# body_add_par(doc, value = "Hello World!", style = "Normal")
# body_add_par(doc, value = "Salut Bretons!", style = "centered")
for (i in 1:nrow(df)) 
{
  text_value <- as.character(df[i,'text_value'])
  text_style <- as.character(df[i,'text_style'])
  body_add_par(doc, value = text_value, style = text_style)
}
print(doc, target = "example.docx")
stefan
  • 90,330
  • 6
  • 25
  • 51
Anonymous
  • 453
  • 1
  • 6
  • 14

1 Answers1

2

The issue is that when adding new paragraphs you have to assign the result back to doc.

library(officer)

df <- data.frame(
  text_level = c(1, 4, 2, 4, 3, 4),
  text_style = c("heading 1", "Normal", "heading 2", "Normal", "heading 3", "Normal"),
  text_value = c("Section 1", "Lorem ipsum.", "Section 1.1", "Lorem ipsum.", "Section 1.1.1", "Lorem ipsum.")
)

doc <- read_docx()
for (i in seq_len(nrow(df)))
{
  text_value <- df[i, "text_value", drop = TRUE]
  text_style <- df[i, "text_style", drop = TRUE]
  doc <- body_add_par(doc, value = text_value, style = text_style)
}
print(doc, target = "example.docx")

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Thanks! Do you know if there's a function or parameter to remove the number prefix before the headers and also left justify the headers? – Anonymous Feb 07 '23 at 06:37
  • 1
    TBMK no. But I might be wrong. I just had a look at the docs and found no function to change the styles defined in the docx. There is a function `change_style` but this is used to "switch" the styles or to map a style on a different one. The "quick" option would be to create a custom template where you set your desired properties. Perhaps @DavidGohel could help to clarify that. – stefan Feb 07 '23 at 06:58
  • 2
    You can use `officer::docx_set_paragraph_style()`, `officer::docx_set_character_style()` to manage styles. I personally like to change the word template as it is very simple and straightforward. There is no function to remove 'number prefix before headers' as asked. In general, there is no function to drop/add style attributes from an existing paragraph (like removing yellow color, changing bold to italic). – David Gohel Feb 07 '23 at 07:58