Документи

Іноді необхідно об’єднати кілька документів в одну. Ви можете зробити це вручну або ви можете використовувати Aspose.Words вставки або додаток функції.

Робота вставки дозволяє вставляти вміст раніше створених документів в новий або існуючий.

У свою чергу, функція Додаток дозволяє додати документ тільки в кінці іншого документа.

Ця стаття пояснює, як вставляти або додавати документ іншим чином і описує загальні властивості, які ви можете застосувати під час вставки або внесення документів.

Вставте документ

Як зазначено вище, в Aspose.Words Документ представлений як дерево вершин, так і операція вставки одного документа в інший є копіювання вузлів з першого документа дерево в другий.

Ви можете вставити документи в різних форматах. Наприклад, ви можете вставити документ через заміну операції, об’єднання поля під час операції з злиття або через закладку.

Ви також можете використовувати insert_document або insert_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")

Приклад наступного коду показує, як вставити документ за допомогою вставка_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())

Наступні підрозділи описують параметри, під час яких можна вставити один документ на інший.

Вставте документ у закладку

Ви можете імпортувати текстовий файл в документ і вставити його прямо після закладки, який ви вказали в документі. Щоб зробити це, створіть закладений пункт, де ви хочете, щоб документ був вставлений.

Приклад кодування показує, як вставити вміст одного документа до закладки в іншому документі:

# 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_document і append_document прийоми ImportFormatMode і ImportFormatOptions як параметри введення. Про нас ImportFormatMode дозволяє контролювати, як форматування документів об’єднано, коли ви імпортуєте вміст з одного документа в інший спосіб, вибравши різні режими форматів, такі як USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTING, і KEEP_DIFFERENT_STYLESй Про нас ImportFormatOptions дозволяє вибрати різні варіанти імпорту, такі як ignore_header_footer, ignore_text_boxes, keep_source_numbering, merge_pasted_lists, і smart_style_behaviorй

Aspose.Words дозволяє налаштовувати візуалізацію отриманого документа при додаванні двох документів у вставку або застосунку Section і PageSetupй Про нас page_setup майно містить всі атрибути розділу, такі як section_start > restart_page_numbering, page_starting_number, orientation, та інші. Найпоширеніший випадок використання - встановити 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")