在页脚中插入带有文字的页码aspose word java

Insert page number with text in footer aspose word java

我想在页脚中插入页码和文本,但是当页脚包含一些文本时,页码和文本在页脚切换位置。 我在使用 aspose words java 库将文档从 html 转换为 word 时这样做。 页脚中的文本是从 html 发送的,我只想添加页码。

在页脚中添加页码的代码:

log.debug("Add page number");
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);

还有,有什么方法可以替换页脚中的整个文本吗?

您可以使用 table 在页脚中添加页码和文本,如下所示:

DocumentBuilder builder = new DocumentBuilder(doc);
// Insert PAGE field into the footer
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.startTable();
// Clear table borders
builder.getCellFormat().clearFormatting();
builder.insertCell();
// Set first cell to 1/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 / 3));
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page
// number and total number of pages.
builder.insertField("PAGE", null);
builder.write("/");
builder.insertField("NUMPAGES", null);
// Align this text to the left.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.LEFT);
builder.insertCell();
// Set the second cell to 2/3 of the page width.
builder.getCellFormat().setPreferredWidth(
PreferredWidth.fromPercent(100 * 2 / 3));
builder.write("(C) 2017 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder.getCurrentParagraph().getParagraphFormat()
.setAlignment(ParagraphAlignment.RIGHT);
builder.endRow();
builder.endTable();

要替换页脚的整个文本,您可以访问页脚,清除所有文本并添加新内容,如下所示:

DocumentBuilder builder = new DocumentBuilder(doc);
Section currentSection = builder.getCurrentSection();
com.aspose.words.HeaderFooter primaryHeader =  currentSection.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
primaryHeader.getParagraphs().clear();
...

我是 Aspose 的开发人员布道师 Tilal Ahmad。