Working with Titles and Heading - Python docx Module

Working with Titles and Heading - Python docx Module

The python-docx module allows you to work with Microsoft Word .docx files. Adding titles and headings is straightforward using this module.

To demonstrate this, let's walk through creating a Word document, adding a title, and adding multiple levels of headings.

1. Installation:

First, if you haven't already installed python-docx, do so using pip:

pip install python-docx 

2. Working with Titles and Headings:

from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # Create a new document doc = Document() # Add a title title = doc.add_heading('Document Title', level=0) # Level 0 is the highest level and is typically used for document titles. title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Center align the title # Add various levels of headings doc.add_heading('Heading Level 1', level=1) doc.add_heading('Heading Level 2', level=2) doc.add_heading('Heading Level 3', level=3) # Save the document doc.save('headings.docx') 

Explanation:

  1. After creating a new document, we add a title using add_heading with a level of 0. This level is typically reserved for document titles and is the highest level.

  2. We then set the alignment of the title to be center-aligned using WD_PARAGRAPH_ALIGNMENT.CENTER.

  3. We proceed to add various levels of headings, demonstrating how to use levels 1 through 3. The python-docx module supports levels from 0 to 9.

  4. Finally, we save the document with the name headings.docx.

That's it! You can now add titles and various levels of headings to your Word documents using the python-docx module.


More Tags

angular-material-stepper react-state-management area copy uipinchgesturerecognizer jsonpath curl-commandline caret eof pem

More Programming Guides

Other Guides

More Programming Examples