Skip to content
Related Articles

Related Articles

Working with Page Break – Python .docx Module
  • Last Updated : 03 Jan, 2021
GeeksforGeeks - Summer Carnival Banner

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 NOT python-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Adding a paragraph
doc.add_heading('Page 1:', 3)
doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
  
# Adding a page break
doc.add_page_break()
  
# Adding a paragraph
doc.add_heading('Page 2:', 3)
doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
  
# Now save the document to a location
doc.save('gfg.docx')

Output:

Page – 1

Page – 2


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :