문서 삽입 및 추가
때로는 여러 문서를 하나로 결합 할 필요가 있습니다. 이 작업을 수동으로 수행하거나Aspose.Words삽입 또는 추가 기능을 사용할 수 있습니다.
삽입 작업을 사용하면 이전에 만든 문서의 내용을 새 문서 또는 기존 문서에 삽입 할 수 있습니다.
추가 기능을 사용하면 다른 문서의 끝 부분에만 문서를 추가할 수 있습니다.
이 문서에서는 다른 방법으로 문서를 삽입하거나 다른 문서에 추가하는 방법과 문서를 삽입하거나 추가하는 동안 적용할 수 있는 공통 속성에 대해 설명합니다.
문서 삽입
위에서 언급했듯이,Aspose.Words에서 문서는 노드 트리로 표현되며,한 문서를 다른 문서에 삽입하는 작업은 첫 번째 문서 트리에서 두 번째 문서 트리로 노드를 복사하는 것입니다.
당신은 다른 방법으로 다양한 위치에 문서를 삽입 할 수 있습니다. 예를 들어 바꾸기 작업,병합 작업 중 병합 필드 또는 책갈피를 통해 문서를 삽입할 수 있습니다.
Microsoft Word에 문서를 삽입하는 것과 유사한InsertDocument또는InsertDocumentInline방법을 사용하여 이전에 가져오지 않고 현재 커서 위치에 전체 문서를 삽입할 수도 있습니다.
다음 코드 예제에서는InsertDocument메서드를 사용하여 문서를 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document srcDoc = new Document(getMyDir() + "Document source.docx"); | |
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx"); | |
DocumentBuilder builder = new DocumentBuilder(dstDoc); | |
builder.moveToDocumentEnd(); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.insertDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
builder.getDocument().save(getArtifactsDir() + "JoinAndAppendDocuments.insertDocument.docx"); |
다음 코드 예제에서는InsertDocumentInline메서드를 사용하여 문서를 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
DocumentBuilder srcDoc = new DocumentBuilder(); | |
srcDoc.write("[src content]"); | |
// Create destination document. | |
DocumentBuilder dstDoc = new DocumentBuilder(); | |
dstDoc.write("Before "); | |
dstDoc.insertNode(new BookmarkStart(dstDoc.getDocument(), "src_place")); | |
dstDoc.insertNode(new BookmarkEnd(dstDoc.getDocument(), "src_place")); | |
dstDoc.write(" after"); | |
Assert.assertEquals("Before after", dstDoc.getDocument().getText().trim()); | |
// Insert source document into destination inline. | |
dstDoc.moveToBookmark("src_place"); | |
dstDoc.insertDocumentInline(srcDoc.getDocument(), ImportFormatMode.USE_DESTINATION_STYLES, new ImportFormatOptions()); | |
Assert.assertEquals("Before [src content] after", dstDoc.getDocument().getText().trim()); |
다음 하위 섹션에서는 한 문서를 다른 문서에 삽입할 수 있는 옵션에 대해 설명합니다.
찾기 및 바꾸기 작업 중에 문서 삽입
찾기 및 바꾸기 작업을 수행하는 동안 문서를 삽입 할 수 있습니다. 예를 들어 문서에[INTRODUCTION]및[CONCLUSION]텍스트가 있는 단락을 포함할 수 있습니다. 그러나 최종 문서에서는 그 단락을 다른 외부 문서에서 얻은 내용으로 대체해야합니다. 이를 위해 바꾸기 이벤트에 대한 처리기를 만들어야 합니다.
다음 코드 예제에서는 나중에 삽입 프로세스에서 사용할 교체 이벤트에 대한 처리기를 만드는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
private static class InsertDocumentAtReplaceHandler implements IReplacingCallback | |
{ | |
public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception | |
{ | |
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx"); | |
// Insert a document after the paragraph, containing the match text. | |
Paragraph para = (Paragraph)args.getMatchNode().getParentNode(); | |
insertDocument(para, subDoc); | |
// Remove the paragraph with the match text. | |
para.remove(); | |
return ReplaceAction.SKIP; | |
} | |
} |
다음 코드 예제에서는 찾기 및 바꾸기 작업 중에 한 문서의 내용을 다른 문서에 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx"); | |
// Set find and replace options. | |
FindReplaceOptions options = new FindReplaceOptions(); | |
{ | |
options.setDirection(FindReplaceDirection.BACKWARD); | |
options.setReplacingCallback(new InsertDocumentAtReplaceHandler()); | |
} | |
// Call the replace method. | |
mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options); | |
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtReplace.docx"); |
Mail Merge작업 {#insert-a-document-during-mail-merge-operation}중에 문서 삽입
Mail Merge작업 중에 병합 필드에 문서를 삽입할 수 있습니다. 예를 들어Mail Merge템플릿에는[요약]과 같은 병합 필드가 포함될 수 있습니다. 그러나 최종 문서에서는 다른 외부 문서에서 얻은 콘텐츠를 이 병합 필드에 삽입해야 합니다. 이를 위해 병합 이벤트에 대한 처리기를 만들어야 합니다.
다음 코드 예제에서는 나중에 삽입 프로세스에서 사용할 병합 이벤트에 대한 처리기를 만드는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
private static class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback | |
{ | |
// This handler makes special processing for the "Document_1" field. | |
// The field value contains the path to load the document. | |
// We load the document and insert it into the current merge field. | |
public void /*IFieldMergingCallback.*/fieldMerging(FieldMergingArgs args) throws Exception | |
{ | |
if ("Document_1".equals(args.getDocumentFieldName())) | |
{ | |
// Use document builder to navigate to the merge field with the specified name. | |
DocumentBuilder builder = new DocumentBuilder(args.getDocument()); | |
builder.moveToMergeField(args.getDocumentFieldName()); | |
// The name of the document to load and insert is stored in the field value. | |
Document subDoc = new Document((String)args.getFieldValue()); | |
insertDocument(builder.getCurrentParagraph(), subDoc); | |
// The paragraph that contained the merge field might be empty now, and you probably want to delete it. | |
if (!builder.getCurrentParagraph().hasChildNodes()) | |
builder.getCurrentParagraph().remove(); | |
// Indicate to the mail merge engine that we have inserted what we wanted. | |
args.setText(null); | |
} | |
} | |
public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) | |
{ | |
// Do nothing. | |
} | |
} |
다음 코드 예제에서는 생성된 처리기를 사용하여 문서를 병합 필드에 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx"); | |
mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler()); | |
// The main document has a merge field in it called "Document_1". | |
// The corresponding data for this field contains a fully qualified path to the document. | |
// That should be inserted to this field. | |
mainDoc.getMailMerge().execute(new String[] { "Document_1" }, new Object[] { getMyDir() + "Document insertion 2.docx" }); | |
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc"); |
책갈피에 문서 삽입
텍스트 파일을 문서로 가져와 문서에서 정의한 책갈피 바로 뒤에 삽입할 수 있습니다. 이렇게 하려면 문서를 삽입할 책갈피된 단락을 만듭니다.
다음 코딩 예제에서는 한 문서의 내용을 다른 문서의 책갈피에 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx"); | |
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx"); | |
Bookmark bookmark = mainDoc.getRange().getBookmarks().get("insertionPlace"); | |
insertDocument(bookmark.getBookmarkStart().getParentNode(), subDoc); | |
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtBookmark.docx"); |
문서 추가
문서에서 기존 문서의 끝까지 추가 페이지를 포함해야 하는 사용 사례가 있을 수 있습니다. 이렇게 하려면AppendDocument메서드를 호출하여 다른 메서드의 끝에 문서를 추가하기만 하면 됩니다.
다음 코드 예제에서는 문서를 다른 문서의 끝에 추가하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document dstDoc = new Document(); | |
dstDoc.getFirstSection().getBody().appendParagraph("Destination document text. "); | |
Document srcDoc = new Document(); | |
srcDoc.getFirstSection().getBody().appendParagraph("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. | |
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
dstDoc.save(getArtifactsDir() + "JoinAndAppendDocuments.KeepSourceFormatting.docx"); |
수동으로 노드 가져오기 및 삽입
Aspose.Words이전 가져오기 요구 사항 없이 문서를 자동으로 삽입하고 추가할 수 있습니다. 그러나 섹션이나 단락과 같은 문서의 특정 노드를 삽입하거나 추가해야 하는 경우 먼저 이 노드를 수동으로 가져와야 합니다.
한 섹션이나 단락을 다른 섹션에 삽입하거나 추가해야 할 때 기본적으로ImportNode방법을 사용하여 첫 번째 문서 노드 트리의 노드를 두 번째 노드로 가져와야합니다. 노드를 가져온 후InsertAfter메서드를 사용하여 참조 노드 뒤에/앞에 새 노드를 삽입해야합니다. 이렇게 하면 문서에서 노드를 가져와 지정된 위치에 삽입하여 삽입 프로세스를 사용자 지정할 수 있습니다.
예를 들어 섹션 수준이 아닌 단락 수준에서 콘텐츠를 추가하려는 경우AppendChild메서드를 사용하여 새 지정된 노드를 자식 노드 목록 끝에 추가할 수도 있습니다.
다음 코드 예제에서는InsertAfter메서드를 사용하여 노드를 수동으로 가져와 특정 노드 뒤에 삽입하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
/// <summary> | |
/// Inserts content of the external document after the specified node. | |
/// Section breaks and section formatting of the inserted document are ignored. | |
/// </summary> | |
/// <param name="insertionDestination">Node in the destination document after which the content | |
/// Should be inserted. This node should be a block level node (paragraph or table).</param> | |
/// <param name="docToInsert">The document to insert.</param> | |
private static void insertDocument(Node insertionDestination, Document docToInsert) | |
{ | |
if (insertionDestination.getNodeType() == NodeType.PARAGRAPH || insertionDestination.getNodeType() == NodeType.TABLE) | |
{ | |
CompositeNode destinationParent = insertionDestination.getParentNode(); | |
NodeImporter importer = | |
new NodeImporter(docToInsert, insertionDestination.getDocument(), 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 (Section srcSection : docToInsert.getSections()) | |
for (Node srcNode : srcSection.getBody()) | |
{ | |
if (srcNode.getNodeType() == NodeType.PARAGRAPH) | |
{ | |
Paragraph para = (Paragraph)srcNode; | |
if (para.isEndOfSection() && !para.hasChildNodes()) | |
continue; | |
} | |
Node newNode = importer.importNode(srcNode, true); | |
destinationParent.insertAfter(newNode, insertionDestination); | |
insertionDestination = newNode; | |
} | |
} | |
else | |
{ | |
throw new IllegalArgumentException("The destination node should be either a paragraph or table."); | |
} | |
} |
즉,페이지 설정,머리글 또는 바닥글과 같은 설정이 가져오는 동안 유지됩니다. 또한 문서를 삽입하거나 추가할 때 서식 설정을 정의하여 두 문서를 함께 결합하는 방법을 지정할 수 있습니다.
문서 삽입 및 추가 {#common-properties-for-insert-and-append-documents}에 대한 공통 속성
InsertDocument및AppendDocument메서드는 모두ImportFormatMode및ImportFormatOptions을 입력 매개 변수로 받아들입니다. ImportFormatMode을 사용하면UseDestinationStyles,KeepSourceFormatting및KeepDifferentStyles과 같은 다른 형식 모드를 선택하여 한 문서에서 다른 문서로 콘텐츠를 가져올 때 문서 서식이 병합되는 방법을 제어할 수 있습니다. ImportFormatOptions는 다음과 같은 다른 가져오기 옵션을 선택할 수 있습니다IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, 그리고SmartStyleBehavior
Aspose.Words을 사용하면Section및PageSetup속성을 사용하여 삽입 또는 추가 작업에서 두 개의 문서를 함께 추가할 때 결과 문서의 시각화를 조정할 수 있습니다. PageSetup속성은 다음과 같은 섹션의 모든 속성을 포함합니다SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, 그리고 다른 사람들도 가장 일반적인 사용 사례는SectionStart속성을 설정하여 추가된 콘텐츠가 동일한 페이지에 표시되는지 또는 새 페이지로 분할되는지를 정의하는 것입니다.
다음 코드 예제에서는 콘텐츠가 두 페이지에 걸쳐 분할되지 않도록 하면서 한 문서를 다른 문서에 추가하는 방법을 보여 줍니다:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document srcDoc = new Document(getMyDir() + "Document source.docx"); | |
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx"); | |
// Set the source document to continue straight after the end of the destination document. | |
srcDoc.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS); | |
// Restart the page numbering on the start of the source document. | |
srcDoc.getFirstSection().getPageSetup().setRestartPageNumbering(true); | |
srcDoc.getFirstSection().getPageSetup().setPageStartingNumber(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. | |
srcDoc.getFirstSection().getPageSetup().setPageWidth(dstDoc.getLastSection().getPageSetup().getPageWidth()); | |
srcDoc.getFirstSection().getPageSetup().setPageHeight(dstDoc.getLastSection().getPageSetup().getPageHeight()); | |
srcDoc.getFirstSection().getPageSetup().setOrientation(dstDoc.getLastSection().getPageSetup().getOrientation()); | |
// Iterate through all sections in the source document. | |
for (Paragraph para : (Iterable<Paragraph>) srcDoc.getChildNodes(NodeType.PARAGRAPH, true)) | |
{ | |
para.getParagraphFormat().setKeepWithNext(true); | |
} | |
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
dstDoc.save(getArtifactsDir() + "JoinAndAppendDocuments.DifferentPageSetup.docx"); |