Insert and Append Documents

Sometimes it is required to combine several documents into one. You can do this manually or you can use Aspose.Words insert or append feature.

The insert operation allows you to insert the content of previously created documents into a new or existing one.

In turn, the append feature allows you to add a document only at the end of another document.

This article explains how to insert or append a document to another one in different ways and describes the common properties that you can apply while inserting or appending documents.

Insert a Document

As mentioned above, in Aspose.Words a document is represented as a tree of nodes, and the operation of inserting one document into another is copying nodes from the first document tree to the second one.

You can insert documents in a variety of locations in different ways. For example, you can insert a document through a replace operation, a merge field during a merge operation, or via a bookmark.

You can also use the insert_document or insert_document_inline method, which is similar to inserting a document in Microsoft Word, to insert a whole document at the current cursor position without any previous importing.

The following code example shows how to insert a document using the insert_document method:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
src_doc = aw.Document(MY_DIR + "Document source.docx")
dst_doc = aw.Document(MY_DIR + "Northwind traders.docx")
builder = aw.DocumentBuilder(dst_doc)
builder.move_to_document_end()
builder.insert_break(aw.BreakType.PAGE_BREAK)
builder.insert_document(src_doc, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)
builder.document.save(ARTIFACTS_DIR + "JoinAndAppendDocuments.insert_document.docx")

The following code example shows how to insert a document using the insert_document_inline method:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
src_doc = aw.DocumentBuilder()
src_doc.write("[src content]")
# Create destination document.
dst_doc = aw.DocumentBuilder()
dst_doc.write("Before ")
dst_doc.insert_node(aw.BookmarkStart(dst_doc.document, "src_place"))
dst_doc.insert_node(aw.BookmarkEnd(dst_doc.document, "src_place"))
dst_doc.write(" after")
self.assertEqual("Before after", dst_doc.document.get_text().strip())
# Insert source document into destination inline.
dst_doc.move_to_bookmark("src_place")
dst_doc.insert_document_inline(src_doc.document, aw.ImportFormatMode.USE_DESTINATION_STYLES, aw.ImportFormatOptions())
self.assertEqual("Before [src content] after", dst_doc.document.get_text().strip())

The following subsections describe the options during which you can insert one document into another.

Insert a Document at Bookmark

You can import a text file into a document and insert it right after a bookmark that you have defined in the document. To do this, create a bookmarked paragraph where you want the document to be inserted.

The following coding example shows how to insert the contents of one document to a bookmark in another document:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
main_doc = aw.Document(MY_DIR + "Document insertion 1.docx")
sub_doc = aw.Document(MY_DIR + "Document insertion 2.docx")
bookmark = main_doc.range.bookmarks.get_by_name("insertionPlace")
self.insert_document(bookmark.bookmark_start.parent_node, sub_doc)
main_doc.save(ARTIFACTS_DIR + "CloneAndCombineDocuments.insert_document_at_bookmark.docx")

Append a Document

You may have a use case where you need to include additional pages from a document to the end of an existing document. To do this, you just need to call the append_document method to add a document to the end of another one.

The following code example shows how to append a document to the end of another document:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
dst_doc = aw.Document()
dst_doc.first_section.body.append_paragraph("Destination document text. ")
src_doc = aw.Document()
src_doc.first_section.body.append_paragraph("Source document text. ")
# Append the source document to the destination document.
# Pass format mode to retain the original formatting of the source document when importing it.
dst_doc.append_document(src_doc, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)
dst_doc.save(ARTIFACTS_DIR + "JoinAndAppendDocuments.keep_source_formatting.docx")

Import and Insert Nodes Manually

Aspose.Words allows you to insert and append documents automatically without any previous importing requirements. However, if you need to insert or append a specific node of your document, such as a section or a paragraph, then first you need to import this node manually.

When you need to insert or append one section or paragraph to another, you essentially need to import the nodes of the first document node tree into the second one using the import_node method. After importing your nodes, you need to use the insert_after / insert_before method to insert a new node after/before the reference node. This allows you to customize the inserting process by importing nodes from a document and inserting it at given positions.

You can also use the append_child method to add a new specified node to the end of the list of child nodes, for example, if you want to append content at the paragraph level instead of at the section level.

The following code example shows how to manually import nodes and insert them after a specific node using the insert_after method:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
@staticmethod
def insert_document(insertion_destination: aw.Node, doc_to_insert: aw.Document):
"""Inserts content of the external document after the specified node.
Section breaks and section formatting of the inserted document are ignored.
:param insertion_destination: Node in the destination document after which the content
Should be inserted. This node should be a block level node (paragraph or table).
:param doc_to_insert: The document to insert.
"""
if insertion_destination.node_type not in (aw.NodeType.PARAGRAPH, aw.NodeType.TABLE):
raise ValueError("The destination node should be either a paragraph or table.")
destination_parent = insertion_destination.parent_node
importer = aw.NodeImporter(doc_to_insert, insertion_destination.document, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)
# Loop through all block-level nodes in the section's body,
# then clone and insert every node that is not the last empty paragraph of a section.
for src_section in doc_to_insert.sections:
for src_node in src_section.as_section().body.get_child_nodes(aw.NodeType.ANY, False):
if src_node.node_type == aw.NodeType.PARAGRAPH:
para = src_node.as_paragraph()
if para.is_end_of_section and not para.has_child_nodes:
continue
new_node = importer.import_node(src_node, True)
destination_parent.insert_after(new_node, insertion_destination)
insertion_destination = new_node

Content is imported into the destination document section by section, which means that settings, such as page setup and headers or footers, are preserved during import. It is also useful to note that you can define formatting settings when you insert or append a document to specify how two documents are joined together.

Common Properties for Insert and Append Documents

Both insert_document and append_document methods accept ImportFormatMode and ImportFormatOptions as input parameters. The ImportFormatMode allows you to control how document formatting is merged when you import content from one document into another by selecting different format modes such as USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTING, and KEEP_DIFFERENT_STYLES. The ImportFormatOptions allows you to select different import options such as ignore_header_footer, ignore_text_boxes, keep_source_numbering, merge_pasted_lists, and smart_style_behavior.

Aspose.Words allows you to adjust the visualization of a resulting document when two documents are added together in an insert or append operation by using the Section and PageSetup. The page_setup property contains all the attributes of a section such as section_start, restart_page_numbering, page_starting_number, orientation, and others. The most common use case is to set the section_start property to define if the added content will appear on the same page or split into a new one.

The following code example shows how to append one document to another while keeping the content from splitting across two pages:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
src_doc = aw.Document(MY_DIR + "Document source.docx")
dst_doc = aw.Document(MY_DIR + "Northwind traders.docx")
# Set the source document to continue straight after the end of the destination document.
src_doc.first_section.page_setup.section_start = aw.SectionStart.CONTINUOUS
# Restart the page numbering on the start of the source document.
src_doc.first_section.page_setup.restart_page_numbering = True
src_doc.first_section.page_setup.page_starting_number = 1
# To ensure this does not happen when the source document has different page setup settings, make sure the
# settings are identical between the last section of the destination document.
# If there are further continuous sections that follow on in the source document,
# this will need to be repeated for those sections.
src_doc.first_section.page_setup.page_width = dst_doc.last_section.page_setup.page_width
src_doc.first_section.page_setup.page_height = dst_doc.last_section.page_setup.page_height
src_doc.first_section.page_setup.orientation = dst_doc.last_section.page_setup.orientation
# Iterate through all sections in the source document.
for para in src_doc.get_child_nodes(aw.NodeType.PARAGRAPH, True):
para = para.as_paragraph()
para.paragraph_format.keep_with_next = True
dst_doc.append_document(src_doc, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)
dst_doc.save(ARTIFACTS_DIR + "JoinAndAppendDocuments.different_page_setup.docx")