2
votes

I want to insert page number in footer alongside with text, but when footer contains some text, page number and text in footer switch places. I am doing this while converting document from html to word using aspose words java library. Text in footer is sent from html and I just want to add page number.

Code for add page number in footer:

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);

Also, is there any way to replace whole text in footer?

1

1 Answers

1
votes

You can add page numbers and text together in footer using table as following:

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();

To replace whole text of footer you may access the footer, clear all text and add new contents as following:

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

I am Tilal Ahmad, developer evangelist at Aspose.