Add Page Numbers to PDF in Java

It is working fine with the latest version.
Can you also provide the sample snippet for aspose pdf jar how to generate page numbers.

@lakshmiM I will move your question into Aspose.PDF forum. My colleagues will help you shortly.

I want to add the some text left align and pagenumber with center align in the footer.

@lakshmiM

In order to achieve your requirements, you can please add text stamp inside PDF document and set its alignment as per your desire. In case you still face any issues, please let us know.

Hi Ali,
I tried the above example. But it is always giving page number as 1.

Document pdfDocument = new Document();
Page page = pdfDocument.getPages().size(); ----------> this line of code is always giving wrong page size. It is always giving as 1. That is why PageNumberStamp is showing as page 1 on all the pages.

@lakshmiM

We tested using one of our sample PDFs and could not replicate the issue. For example, please check the below complete code snippet:

// Create a document object
Document doc = new Document();
// Add a page to the document
Page page = doc.getPages().add();
// Create a text fragment and add it to the page
TextFragment text = new TextFragment("Hello World!");
page.getParagraphs().add(text);
// Create a page number stamp object
PageNumberStamp stamp = new PageNumberStamp();
// Set the format of the page number
stamp.setFormat("Page #");
// Set the starting number of the page number
stamp.setStartingNumber(1);
// Set the numbering style of the page number
stamp.setNumberingStyle(NumberingStyle.Arabic);
// Loop through all the pages of the document
for (int i = 1; i <= doc.getPages().size(); i++) {
// Get the current page
Page p = doc.getPages().get_Item(i);
// Add the page number stamp to the current page
stamp.put(p);
}
// Save the document
doc.save("output.pdf");

Can you please make sure that the you are using a valid or 30-days free temporary license? In case you still notice any issues, please share your sample PDF document with us along with the sample code snippet that you are using. We will test the scenario in our environment and address it accordingly.