Chèn và nối tài liệu

Đôi khi cần phải kết hợp nhiều tài liệu thành một. Bạn có thể thực hiện việc này theo cách thủ công hoặc bạn có thể sử dụng tính năng chèn hoặc nối thêm Aspose.Words.

Thao tác chèn cho phép bạn chèn nội dung của tài liệu đã tạo trước đó vào tài liệu mới hoặc hiện có.

Đổi lại, tính năng chắp thêm cho phép bạn chỉ thêm tài liệu vào cuối tài liệu khác.

Bài viết này giải thích cách chèn hoặc nối thêm tài liệu vào tài liệu khác theo nhiều cách khác nhau và mô tả các thuộc tính phổ biến mà bạn có thể áp dụng khi chèn hoặc nối thêm tài liệu.

Chèn một tài liệu

Như đã đề cập ở trên, trong Aspose.Words một tài liệu được biểu diễn dưới dạng cây các nút và thao tác chèn tài liệu này vào tài liệu khác là sao chép các nút từ cây tài liệu đầu tiên sang cây tài liệu thứ hai.

Bạn có thể chèn tài liệu vào nhiều vị trí khác nhau theo nhiều cách khác nhau. Ví dụ: bạn có thể chèn tài liệu thông qua thao tác thay thế, trường hợp nhất trong thao tác hợp nhất hoặc qua dấu trang.

Bạn cũng có thể sử dụng phương pháp insert_document hoặc insert_document_inline, tương tự như chèn tài liệu bằng Microsoft Word, để chèn toàn bộ tài liệu vào vị trí con trỏ hiện tại mà không cần nhập trước đó.

Ví dụ mã sau đây cho thấy cách chèn tài liệu bằng phương pháp chèn_tài liệu:

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

Ví dụ mã sau đây cho thấy cách chèn tài liệu bằng phương pháp chèn_document_inline:

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

Các phần phụ sau đây mô tả các tùy chọn trong đó bạn có thể chèn tài liệu này vào tài liệu khác.

Chèn tài liệu vào Bookmark

Bạn có thể nhập tệp văn bản vào tài liệu và chèn nó ngay sau dấu trang mà bạn đã xác định trong tài liệu. Để thực hiện việc này, hãy tạo một đoạn được đánh dấu nơi bạn muốn chèn tài liệu.

Ví dụ mã hóa sau đây cho thấy cách chèn nội dung của một tài liệu vào dấu trang trong tài liệu khác:

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

Nối thêm một tài liệu

Bạn có thể có một trường hợp sử dụng trong đó bạn cần đưa các trang bổ sung từ tài liệu vào cuối tài liệu hiện có. Để thực hiện việc này, bạn chỉ cần gọi phương thức append_document để thêm tài liệu vào cuối tài liệu khác.

Ví dụ mã sau đây cho biết cách nối thêm tài liệu vào cuối tài liệu khác:

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

Nhập và chèn nút theo cách thủ công

Aspose.Words cho phép bạn chèn và nối tài liệu tự động mà không cần bất kỳ yêu cầu nhập nào trước đó. Tuy nhiên, nếu bạn cần chèn hoặc nối thêm một nút cụ thể trong tài liệu của mình, chẳng hạn như một phần hoặc một đoạn văn, thì trước tiên bạn cần nhập nút này theo cách thủ công.

Khi bạn cần chèn hoặc nối một phần hoặc đoạn văn vào phần khác, về cơ bản bạn cần nhập các nút của cây nút tài liệu đầu tiên vào cây nút thứ hai bằng phương pháp import_node. Sau khi nhập các nút của mình, bạn cần sử dụng phương thức insert_after / insert_before để chèn một nút mới sau/trước nút tham chiếu. Điều này cho phép bạn tùy chỉnh quá trình chèn bằng cách nhập các nút từ tài liệu và chèn nó vào các vị trí nhất định.

Bạn cũng có thể sử dụng phương pháp append_child để thêm một nút được chỉ định mới vào cuối danh sách các nút con, ví dụ: nếu bạn muốn nối thêm nội dung ở cấp đoạn văn thay vì ở cấp phần.

Ví dụ về mã sau đây cho thấy cách nhập thủ công các nút và chèn chúng sau một nút cụ thể bằng phương pháp 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

Nội dung được nhập vào tài liệu đích theo từng phần, có nghĩa là các cài đặt, chẳng hạn như thiết lập trang và đầu trang hoặc chân trang, được giữ nguyên trong quá trình nhập. Cũng hữu ích khi lưu ý rằng bạn có thể xác định cài đặt định dạng khi chèn hoặc nối thêm tài liệu để chỉ định cách hai tài liệu được nối với nhau.

Thuộc tính chung để chèn và nối tài liệu

Cả hai phương thức insert_documentappend_document đều chấp nhận ImportFormatModeImportFormatOptions làm tham số đầu vào. ImportFormatMode cho phép bạn kiểm soát cách hợp nhất định dạng tài liệu khi bạn nhập nội dung từ tài liệu này sang tài liệu khác bằng cách chọn các chế độ định dạng khác nhau như USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTINGKEEP_DIFFERENT_STYLES. ImportFormatOptions cho phép bạn chọn các tùy chọn nhập khác nhau như ignore_header_footer, ignore_text_boxes, keep_source_numbering, merge_pasted_listssmart_style_behavior.

Aspose.Words cho phép bạn điều chỉnh trực quan hóa tài liệu kết quả khi hai tài liệu được thêm vào cùng nhau trong thao tác chèn hoặc nối thêm bằng cách sử dụng SectionPageSetup. Thuộc tính page_setup chứa tất cả các thuộc tính của một phần như section_start, restart_page_numbering, page_starting_number, orientation và các thuộc tính khác. Trường hợp sử dụng phổ biến nhất là đặt thuộc tính section_start để xác định xem nội dung được thêm sẽ xuất hiện trên cùng một trang hay được chia thành một trang mới.

Ví dụ về mã sau đây cho thấy cách nối một tài liệu này vào một tài liệu khác trong khi vẫn giữ cho nội dung không bị chia thành hai trang:

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