Aspose words合并word包含toc,toc的宽度和被合并文件的宽度不一致

Hi , 我的问题,合并word包含toc,toc的宽度和被合并文件不一致。帮忙看下,感谢

技术栈:jdk21 + spring boot 3.2.5 + aspose-words-21.5.0-jdk17
合并代码:

public static final String tocFontName = "Arial";

    private static final License ASPOSE_LICENSE = new License();
    static {
        try {
            //Aspose.WordsProductFamily.lic license.xml
            URL resource = AsposeUtil.class.getClassLoader().getResource("license.xml");
            if (resource != null) {
                InputStream stream = resource.openStream();
                ASPOSE_LICENSE.setLicense(stream);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        String prefixPath = "D:\\WorkSpace\\Test\\merge\\6\\";
        Map<String, String> names = Map.of("Table 14.1.1.1.1_Shell_Solution_HC3_Oncology_01_dev_test_Dong-0625-Test-01-IN63935_Production_20250701 (6).docx",
                "Table 14.1.1.1.1_Shell_Solution_HC3_Oncology_01_dev_test_Dong-0625-Test-01-IN63935_Production_20250701 (6)",
                "Table 14.1_Shell_Solution_HC3_Oncology_01_dev_test_Dong-0625-Test-01-IN63935_Production_20250701 (3).docx",
                "Table 14.1_Shell_Solution_HC3_Oncology_01_dev_test_Dong-0625-Test-01-IN63935_Production_20250701 (3)");
        String mergeDocName = "merge6.docx";
        String savePath = prefixPath + File.separator + mergeDocName;
        String tempPath = prefixPath + File.separator + "temp";
        //setFontDir();
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();
        }
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.pushFont();
        builder.getFont().setSize(18);
        builder.getFont().setNameAscii(tocFontName);
        ParagraphFormat paragraphFormat = builder.getParagraphFormat();
        paragraphFormat.setLineSpacing(12);
        paragraphFormat.setAlignment(ParagraphAlignment.CENTER);
        builder.writeln("Table of Contents");
        builder.popFont();
        builder.writeln("");
        FieldToc fieldToc = (FieldToc) builder.insertField(FieldType.FIELD_TOC, true);
        fieldToc.setEntryLevelRange("1-3");
        fieldToc.setInsertHyperlinks(true);
        LoadOptions loadOptions = new LoadOptions();
        loadOptions.setTempFolder(tempPath);
        long start = System.currentTimeMillis();
        loadOptions.setLoadFormat(ImportFormatMode.KEEP_SOURCE_FORMATTING);
        names.forEach((fileName, tocTitle) -> {
            try {
                Document src = new Document(prefixPath + File.separator + fileName, loadOptions);
                DocumentBuilder srcBuilder = new DocumentBuilder(src);
                FieldTC fieldTc = (FieldTC) srcBuilder.insertField(FieldType.FIELD_TOC_ENTRY, true);
                fieldTc.setText(tocTitle);
                fieldTc.setEntryLevel("1");
                doc.appendDocument(src, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getFont().setSize(12);
        doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getParagraphFormat().setLineSpacing(12);
        long ss1 = System.currentTimeMillis();
        doc.updateFields();
        long ss2 = System.currentTimeMillis();
        doc.setWarningCallback(warningInfo -> {
            if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) {
            } else {
            }
        });
        doc.save(savePath, SaveFormat.DOCX);

    }

合并文件和合并后的文件。
merge-word.zip (30.8 KB)

@imzdong

Cause

The issue you’re encountering with the Table of Contents (TOC) width not matching the merged document’s width is likely due to differences in the page setup or margins between the original documents and the merged document. When merging documents, the TOC may not automatically adjust to the new document’s layout.

Solution

To ensure the TOC width aligns with the merged document, adjust the page setup and margins before inserting the TOC. Follow these steps:

  1. Set Page Setup: Ensure that the page setup (size, margins) of the merged document matches that of the source documents.
  2. Update TOC Field: After merging the documents, update the TOC field to reflect the correct layout.

Code

Here’s a modified version of your merging code that includes setting the page setup for the merged document:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set page setup for the merged document
PageSetup pageSetup = doc.getFirstSection().getPageSetup();
pageSetup.setPaperSize(PaperSize.A4);
pageSetup.setTopMargin(72);
pageSetup.setBottomMargin(72);
pageSetup.setLeftMargin(72);
pageSetup.setRightMargin(72);

// Insert TOC
builder.writeln("Table of Contents");
FieldToc fieldToc = (FieldToc) builder.insertField(FieldType.FIELD_TOC, true);
fieldToc.setEntryLevelRange("1-3");
fieldToc.setInsertHyperlinks(true);

// Merge documents
names.forEach((fileName, tocTitle) -> {
    try {
        Document src = new Document(prefixPath + File.separator + fileName, loadOptions);
        doc.appendDocument(src, ImportFormatMode.KEEP_SOURCE_FORMATTING);
    } catch (Exception e) {
        e.printStackTrace();
    }
});

// Update TOC
doc.updateFields();
doc.save(savePath, SaveFormat.DOCX);

Next Steps

  1. Run the modified code to merge your documents.
  2. Check the TOC width in the merged document.
  3. If the issue persists, verify the individual document settings before merging.

Please let me know if you need further assistance!

需要我的是插入toc模式,而不是靠doc.updateFields();刷新生成的

@imzdong 请尝试最新的 25.6 版本。 以下是我的输出结果:

output.docx (18.9 KB)

@vyacheslav.deryushev ok thanks

1 Like