1

I'd like to add content at the beginning of a Word document. Important note: this document already has content, I want to add content BEFORE text that is already in this file. something like:

# input file text
blah blah blah
blah blah blah
# output file text
This added paragraph1
blah blah blah
blah blah blah

I'm using OfficeR package in R. I'm trying to open a file, add a line at the beginning of file, and save it with a different name:

library('officer')
sample_doc <- read_docx("inputfile.docx")
cursor_begin(sample_doc)
sample_doc <-  body_add_par(sample_doc, "This added paragraph1")
print(sample_doc, target = "outputfile.docx")

Unfortunately, the cursor_begin command doesn't seem to work, the new paragraph is appended to the end of the document. I don't know if I'm reading something wrong in the documentation. Could someone give me a hint?

EDIT:

There was a suggestion below to use pos="before" to indicate where to insert the text - before or after the cursor. For example

body_add_par(sample_doc, "This added paragraph1", pos="before")

Unfortunately, this solution works only for docs with one paragraph of text. With only one paragraph of text, setting pos='before' moves the text up a line whether or not you use cursor_begin. Using this solution for more than one paragraph stil gives something like:

# input file text
blah blah blah
blah blah blah
# output file text
blah blah blah
This added paragraph1
blah blah blah

so it is not the solution i'm lookin for.

kwadratens
  • 187
  • 15

1 Answers1

3

Actually, I think that cursor_begin is working, but maybe not the way that you think. It is selecting the first paragraph. But when you use body_add_par the default is pos="after". You need "before". Also, when you call cursor_begin you must save the result back into sample_doc.

This should work for you:

library('officer')
sample_doc <- read_docx("inputfile.docx")
sample_doc <- cursor_begin(sample_doc)
sample_doc <- body_add_par(sample_doc, 
    "This added paragraph1", pos="before")
print(sample_doc, target = "outputfile.docx")
G5W
  • 36,531
  • 10
  • 47
  • 80
  • Editing my answer to match what I actually did. – G5W Jan 03 '23 at 14:46
  • 1
    I did test my code with multiple paragraphs, and it worked for me. Your code still says `cursor_begin(sample_doc)` did you change that to `sample_doc <- cursor_begin(sample_doc)` If you made BOTH of my changes to your code and it is still not working, please indicate what version of officer you are using. – G5W Jan 03 '23 at 15:11
  • Sorry, i see that now: the key is "sample_doc <- cursor_begin(sample_doc)", and You're right. Now everything is working. Thank You and sorry again. – kwadratens Jan 03 '23 at 15:31