4

I'm trying to add line breaks using body_replace_all_text or body_add_par but am having no joy. Using \r\n shows correctly in OSX TextEdit, but not in Word.

An example:

library(officer)
library(tidyverse)

read_docx() %>% 
  body_add_par("Oneline\r\n\r\nAnother line") %>% 
  print(target = "example.docx")

is there a right way to do this?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
bjw
  • 2,046
  • 18
  • 33

3 Answers3

5

You will have to call body_add_par each time you want to add a paragraph (a paragraph of text ends with a new line):

library(officer)
library(tidyverse)

read_docx() %>% 
  body_add_par("Oneline") %>% 
  body_add_par("Another line") %>% 
  print(target = "example.docx")
David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • 3
    Thanks for the answer. It would be really nice to add a helper to add multiple lines/paras of plain text. – bjw Jun 04 '18 at 14:02
  • Thanks you. It's pretty useless in that way. – Karol Daniluk Sep 01 '22 at 07:29
  • I am not sure if I understand your comment @KarolDaniluk. You want me to know that this function is useless? – David Gohel Sep 01 '22 at 09:01
  • I mean it would be nice indeed if they added function to add plain text. Now it is very slow witch in my opinion makes it useless to generate big documents. – Karol Daniluk Sep 01 '22 at 09:08
  • In fact I did. I don't try to be mean or vicious, just stating the facts. I found a simple workaround by writing all text into the txt file and using shell to open Word and paste the file content. Takes 3 seconds. – Karol Daniluk Sep 05 '22 at 07:43
3

An alternative way that I found was to modify in Word.

library(officer)
library(tidyverse)

read_docx() %>% 
  body_add_par("Oneline(LineBreak)Another line") %>% 
  print(target = "example.docx")

Then in Word, press Ctrl + H and change all "(LineBreak)" to "^p".

Not a fancy idea but it worked for me as a band aid solution.

Owen Cho
  • 51
  • 1
1

Here is a simple workaround with splitting the string into a vector and writing each line separately. Unfortunately it is very slow.

library(officer)
library(tidyverse)

doc <- read_docx()
text <- "Oneline\r\n\r\nAnother line" %>% strsplit('\r\n') %>% unlist()
for (t in text){
  body_add_par(doc, t)
}
print(doc, target = "example.docx")
Karol Daniluk
  • 506
  • 4
  • 10