Working with Page Break – Python .docx Module
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module.
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also add page breaks using this module. To add a page break in a word document you can use add_page_break() method.
This method adds a hard page break in the document and creates a new paragraph object. This is an essential paragraph styling tool. Whenever the requirement is to start a new page, mostly cases where you want a new page for a new topic, a single method is sufficient. It helps increase clarity and improves presentation to reap the most of word.
Syntax: doc.add_page_break()
Approach
- Import module
- Create docx object
- Add add_page_break() function whenever the control need to be shift to a new page
- Save document.
Example:
Python3
import docx
doc = docx.Document()
doc.add_heading( 'GeeksForGeeks' , 0 )
doc.add_heading( 'Page 1:' , 3 )
doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.' )
doc.add_page_break()
doc.add_heading( 'Page 2:' , 3 )
doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.' )
doc.save( 'gfg.docx' )
|
Output:
Page – 1
Page – 2
Last Updated :
03 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...