How to use merge documents together with Document.Append

Problem

Prior to WordWriter 4.5.0, the only way to merge entire documents was to use InsertAfter. Starting in WordWriter 4.5.0, Document.Append() was introduced as an improved way to merge documents together.

This post covers the behavior of Document.Append().

Solution

The default behavior of Document.Append() is creating a section-page break between the original document and the inserted document:

 documentOne.Append(newDocument); 

To merge the two documents so they appear continuous, simply change the section break type to be continuous:

int mySectionsCount = thisDocument.Sections.Length;
thisDocument.Append(otherDocument);
thisDocument.Sections[mySectionsCount].Break = Section.BreakType.Continuous;

Example:

For a more complicated example, here we want to insert into our current work document (thisDocument) a header from one template document and body content from another template document. Note that we want both the header and the body to be on the same page, so we change the type of the section break at the tail of the header to continuous.

// adding header document
Document headerDocument = Wapp.Open(_headerSource);
thisDocument.Append(headerDocument);


// adding body document
Document bodyDocument = Wapp.Open(_bodySource);
int sectionCount = thisDocument.Sections.Length;
thisDocument.Append(bodyDocument);
thisDocument.Sections[sectionCount].Break = Section.BreakType.Continuous;

Note that if the initial document (the one you append into) is empty, we get a blank page at the beginning of the document. To fix that we need to delete the first empty section:

 thisDocument.Sections[0].DeleteElement(); 

All other InsertAfter operations that don’t deal with sections should stay unchanged.

Related posts: