Search code examples
rofficer

How to delete blank line at beginning of docx from officer


I am using officer for R to create a a Word (docx) document. Here is the code:

library(officer)
library(magrittr)

my_docx = read_docx() %>% 
  # cursor_begin() %<>% 
  body_add_par("Hello here is a test sentence to see if there is a blank line above it.", style = "Normal") %>% 
  print(target = "test.docx")

It creates a docx document that has a blank line at the top above the sentence. It isn't spacing before the font style that is set in the Style of the font. I have uncommented cursor_begin() but the blank line remains. How can I get rid of this?

Any help is appreciated!


Solution

  • To delete a paragraph, you need to use function body_remove(). See documentation here: https://davidgohel.github.io/officer/articles/word.html#remove-content

    library(officer)
    library(magrittr)
    
    my_docx <- read_docx() %>% 
      cursor_begin() %>% body_remove() %>% 
      body_add_par("Hello here is a test sentence to see if there is a blank line above it.", 
                   style = "Normal") %>% 
      print(target = "test.docx")