Home > other >  How to add text at beginning of Word document?
How to add text at beginning of Word document?

Time:01-04

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.

CodePudding user response:

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")
  • Related