插入和附加文档

有时需要将多个文档合并为一个。您可以手动执行此操作,也可以使用 Aspose.Words 插入或附加功能。

插入操作允许您将先前创建的文档的内容插入到新的或现有的文档中。

反过来,附加功能允许您仅在另一个文档的末尾添加文档。

本文介绍如何以不同的方式将一个文档插入或附加到另一个文档,并介绍在插入或附加文档时可以应用的常见属性。

插入文档

如上所述,在 Aspose.Words 中,文档被表示为节点树,将一个文档插入另一个文档的操作是将节点从第一个文档树复制到第二个文档树。

您可以用不同的方式将文档插入到不同的位置。例如,您可以通过替换操作、合并操作期间的合并字段或通过书签插入文档。

您还可以使用insert_documentinsert_document_inline方法,类似于在Microsoft Word中插入文档,在当前光标位置插入整个文档,而无需先前导入。

以下代码示例演示如何使用 插入文档 方法插入文档:

# 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")

以下代码示例演示如何使用 内联插入文档 方法插入文档:

# 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())

以下小节介绍了可以将一个文档插入到另一个文档中的选项。

在书签处插入文档

您可以将文本文件导入到文档中,并将其插入到文档中定义的书签后面。为此,请在要插入文档的位置创建一个带书签的段落。

以下编码示例显示如何将一个文档的内容插入到另一文档的书签中:

# 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_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")

手动导入和插入节点

Aspose.Words 允许您自动插入和附加文档,无需任何先前的导入要求。但是,如果您需要插入或附加文档的特定节点(例如节或段落),那么首先需要手动导入该节点。

当您需要将一个部分或段落插入或附加到另一个部分或段落时,本质上需要使用 import_node 方法将第一个文档节点树的节点导入到第二个文档节点树中。导入节点后,您需要使用 insert_after / insert_before 方法在引用节点之后/之前插入新节点。这允许您通过从文档导入节点并将其插入给定位置来自定义插入过程。

您还可以使用 append_child 方法将新的指定节点添加到子节点列表的末尾,例如,如果您想在段落级别而不是节级别追加内容。

以下代码示例展示了如何使用 insert_after 方法手动导入节点并将其插入到特定节点之后:

# 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

内容将逐节导入到目标文档中,这意味着在导入过程中会保留页面设置和页眉或页脚等设置。值得注意的是,您可以在插入或附加文档时定义格式设置,以指定两个文档如何连接在一起。

插入和追加文档的通用属性

insert_documentappend_document 方法都接受 ImportFormatModeImportFormatOptions 作为输入参数。当您通过选择不同的格式模式(例如 USE_DESTINATION_STYLESKEEP_SOURCE_FORMATTINGKEEP_DIFFERENT_STYLES)将内容从一个文档导入到另一个文档时,ImportFormatMode 允许您控制文档格式的合并方式。 ImportFormatOptions 允许您选择不同的导入选项,例如 ignore_header_footerignore_text_boxeskeep_source_numberingmerge_pasted_listssmart_style_behavior

当使用 SectionPageSetup 在插入或追加操作中将两个文档添加在一起时,Aspose.Words 允许您调整结果文档的可视化。 page_setup 属性包含节的所有属性,例如 section_startrestart_page_numberingpage_starting_numberorientation 等。最常见的用例是设置 section_start 属性来定义添加的内容是出现在同一页面上还是拆分为新页面。

以下代码示例演示如何将一个文档追加到另一个文档,同时防止内容拆分为两页:

# 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")