aspose.words生成word文档(.dox、.docx等)时,生成目录后,目录中的页码和实际页码不对应,代码中更新域都没用

    xiaoxiao2021-12-14  19

    插入目录以及设置目录样式的代码:

    //将光标移到目录书签 builder.moveToBookmark("TOC"); builder.insertBreak(BreakType.PAGE_BREAK); //设置目录的格式 //“目录”两个字居中显示、加粗、搜宋体 builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.setBold(true); builder.getFont().setName(FontName.SONG); builder.writeln("目录"); //清清除所有样式设置 builder.getParagraphFormat().clearFormatting(); //目录居左 builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT); //插入目录,这是固定的 builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); field.update(); doc.updateFields();// 更新域 doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getFont().setSize(FontSize.FONT105); //改变目录的字体大小 doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_2).getFont().setSize(FontSize.FONT105); //改变目录的字体大小 doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getFont().setSize(FontSize.FONT105); //改变目录的字体大小 doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getParagraphFormat().setLineSpacing(18);//改变目录行距 merge.updatePageLayout(); merge.updateFields(); field.update(); //读取配置文件获取word路径 Properties properties = new Properties(); InputStream in = this.getClass().getResourceAsStream("/config/docPath.properties"); properties.load(in); reportDocPath = properties.get("docPath").toString(); System.out.println("————————————路径:" + reportDocPath); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String now = sdf.format(new Date()).replaceAll("-", "."); doc.save(reportDocPath + now + ".doc");

    可以看出,在生成目录后我尝试进行了许多关于文档、域的更新,然而,word并不为之所动,目录中的页码和实际页码依然纹丝不动的不对应着,如图: 目录:

    word文档内部:

    后期也做了更多尝试,比如宏什么的,都没用,和之前说的word文档在WPS中的兼容性一样,这个问题的源头依然只是一个非常不起眼的小属性,也是随着WPS兼容性的解决随之解决的,看到之后的确哭笑不得呢~当初我可是因为这个页码的问题苦苦追寻了一个多星期的答案(···未果···)

    解决方案:

    检查你的代码,看看是否存在类似于这行的代码:

    builder.getCellFormat().setWidth(PreferredWidthType.POINTS);

    如果有,恭喜你,注释掉这一行你就得救了!重新生成一份word吧,Here comes the sunshine! b( ̄▽ ̄)d

    真的,当我注释掉这一行后,整个人都不好了,就这一行属性设置,引起了目录页码和实际页码不对应、WPS显示一团糟两个大问题,惨不惨!

    快去试试吧!

    转载请注明原文地址: https://ju.6miu.com/read-965530.html

    最新回复(0)