This tutorial contains all the information on how to insert page numbers in Word using Java by providing steps and a runnable sample code along with a detailed description. The given steps depict the complete program logic that can be followed to write a simple application to add page numbers in Word using Java and then save the resultant file in DOCX or DOC file format. You will also learn to move to different parts of the header and footer sections within a Word file.
Steps to Insert Page Number in Word using Java
- Take the necessary steps to add Aspose.Words for Java in your application
- Load the source Word file to add page number using the Document class object
- Instantiate a DocumentBuilder class object using the loaded Word file
- Move control to the primary footer section using the DocumentBuilder object
- Add fields like PAGE and NUMPAGES along with a title and a separator
- Save the resultant Word file after adding the page number in the footer
These steps describe how to put page number in Word using Java by sharing the details of the methods and properties in the DocumentBuilder class that can be used for adding page number in the header or footer of a Word file. First, we load the source Word file and instantiate the DocumentBuilder class object that contains features like moving to different sections of the documents for working with the contents and adding different fields in the header and footer as per the requirement.
Code to Insert Page Number using Java
This code demonstrates how to put numbers on pages in Word using Java by using different classes and methods like moveToHeaderFooter() method is used to move the control to the footer by using FOOTER_PRIMARY enumerator, however, you may also use HEADER_PRIMARY, HEADER_FIRST, HEADER_EVEN, FOOTER_EVEN, and FOOTER_FIRST. Similarly, you may add other fields as well like NUMWORDS, NUMCHARS, etc. by using the insertField() method along with the option to add titles and separators using the write() method.
In this article, we have learned to insert page numbers in Word using Java. If you want to learn the process to add comments in a Word document, refer to the article on how to add comments in Word using Java.