Aspose.Words For JAVA文档合并的问题

使用产品:Aspose.Words For JAVA

附件文档说明:“文件1”是原文档,“文件2”是需要附加的文档。

需求:我需要把“文件2”插入到’文件1’里,插入的时候我希望能够插入到“文件1”文档里的任意目录层级下,并且插入完成后,能够更新目录,请问可以实现吗?

test.zip (174.5 KB)

您好 @SupportDhorde,

下面给出的示例代码将 file2 插入到 file1 并设置标题所需的级别:

    public static void main(String[] args) throws Exception {
        License lic = new License();
        lic.setLicense("Aspose.Words.Java.lic");

        Document doc2 = new Document("文件2.docx");

        DocumentBuilder builder = new DocumentBuilder(doc2);
        builder.moveToParagraph(0,0);
        Paragraph doc2Para1 = builder.getCurrentParagraph();
        builder.moveToParagraph(1, 0);
        Paragraph doc2Para2 = builder.getCurrentParagraph();

        /* ===================================================== */
        Document doc1 = new Document("文件1.docx");
        doc2Para1.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_4);
        doc2Para2.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_5);

        AppendAndSave(doc1, doc2, "merged1.docx");

        /* ===================================================== */
        doc1 = new Document("文件1.docx");

        doc2Para1.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3);
        doc2Para2.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_4);

        AppendAndSave(doc1, doc2, "merged2.docx");

        /* ===================================================== */
        doc1 = new Document("文件1.docx");

        doc2Para1.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
        doc2Para2.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3);

        AppendAndSave(doc1, doc2, "merged3.docx");

        /* ===================================================== */
        doc1 = new Document("文件1.docx");

        doc2Para1.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
        doc2Para2.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);

        AppendAndSave(doc1, doc2, "merged4.docx");
    }

    private static void AppendAndSave(Document doc1, Document doc2, String docFilename) throws Exception {
        doc1.appendDocument(doc2, ImportFormatMode.USE_DESTINATION_STYLES);

        doc1.updateFields();
        doc1.updatePageLayout();

        doc1.save(docFilename);
    }

merged_1_2_3_4.zip (184.2 KB)

以下是可能有帮助的文档链接:

[Document.moveToParagraph](https://reference.aspose.com/words/java/com.aspose.words/DocumentBuilder.moveToParagraph(int,int))
[ParagraphFormat.setStyleIdentifier](https://reference.aspose.com/words/java/com.aspose.words/ParagraphFormat#StyleIdentifier)