문서 삽입 및 추가

때로는 여러 문서를 하나로 통합해야 하는 경우도 있습니다. 이 작업을 수동으로 수행하거나 Aspose.Words 삽입 또는 추가 기능을 사용할 수 있습니다.

삽입 작업을 사용하면 이전에 생성된 문서의 내용을 새 문서나 기존 문서에 삽입할 수 있습니다.

또한 추가 기능을 사용하면 다른 문서의 끝에만 문서를 추가할 수 있습니다.

이 문서에서는 다양한 방법으로 문서를 다른 문서에 삽입하거나 추가하는 방법을 설명하고 문서를 삽입하거나 추가하는 동안 적용할 수 있는 공통 속성에 대해 설명합니다.

문서 삽입

위에서 언급했듯이 Aspose.Words에서 문서는 노드 트리로 표현되며, 한 문서를 다른 문서에 삽입하는 작업은 첫 번째 문서 트리에서 두 번째 문서 트리로 노드를 복사하는 것입니다.

다양한 위치에 다양한 방법으로 문서를 삽입할 수 있습니다. 예를 들어 바꾸기 작업, 병합 작업 중 병합 필드 또는 책갈피를 통해 문서를 삽입할 수 있습니다.

Microsoft Word에 문서를 삽입하는 것과 유사한 insert_document 또는 insert_document_inline 방법을 사용하면 이전에 가져오지 않고도 현재 커서 위치에 전체 문서를 삽입할 수 있습니다.

다음 코드 예제에서는 insert_document 메서드를 사용하여 문서를 삽입하는 방법을 보여줍니다

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

다음 코드 예제에서는 insert_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_documentappend_document 방법 모두 ImportFormatModeImportFormatOptions를 입력 매개변수로 허용합니다. ImportFormatMode을 사용하면 USE_DESTINATION_STYLES, KEEP_SOURCE_FORMATTING, KEEP_DIFFERENT_STYLES와 같은 다양한 형식 모드를 선택하여 한 문서에서 다른 문서로 콘텐츠를 가져올 때 문서 형식이 병합되는 방식을 제어할 수 있습니다. ImportFormatOptions를 사용하면 ignore_header_footer, ignore_text_boxes, keep_source_numbering, merge_pasted_listssmart_style_behavior와 같은 다양한 가져오기 옵션을 선택할 수 있습니다.

Aspose.Words를 사용하면 SectionPageSetup을 사용하여 삽입 또는 추가 작업에서 두 문서를 함께 추가할 때 결과 문서의 시각화를 조정할 수 있습니다. 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")