This tutorial is designed to guide on how to put page number in Word using Python by providing detailed steps and a runnable sample code. You will get information about roaming in a loaded Word file and add different contents like page numbers in its footer. The sample code at the end will insert a page number in word using python along with the total number of pages and then finally save the resultant Word file as DOCX, DOC, or any other MS Word supported format.
Steps to Add Page Numbers in Word using Python
- Establish the environment to use Aspose.Words for Python via .NET to add page number
- Load the source Word file using the Document class object
- Create DocumentBuilder class object for writing and moving in the loaded document
- Move to the footer section
- Write text, page number, and the total number of pages
- Save the output word file with page numbers in it
These steps describe how to insert page numbers in Word using Python by first sharing the environment details and then details to load and insert contents in the Word file. First, you have to load the source Word file and then instantiate the DocumentBuilder class object that allows you to roam around the document and insert different contents like the page field in this article. You can format the page number properly using the appropriate text along with the page number if required.
Code to Insert Page Number using Python
This code demonstrates how to add page numbers using Python by using different methods and properties in the DocumentBuilder class. It allows moving to the header or footer section of the document using the move_to_header_footer() method by providing the HeaderFooterType as FOOTER_PRIMARY. You can write constant text using the write() method and insert_field() method to write different fields like page number and the total number of pages displayed in a pretty format.
This tutorial has guided us to insert page numbers and other fields in the header or footer section of a document. If you want to learn the process of converting a Word file to PDF, refer to the article on how to convert Word to PDF using Python.