Python: Add or Remove Shapes in Word

2024-04-30 01:07:31 Written by Koohji

In the modern office environment, Microsoft Word has become an indispensable part of our daily work and study. Whether it's writing reports, creating resumes, or designing promotional materials, Word provides us with a rich set of features and tools. Among them, the function of adding shapes is particularly popular among users because it allows us to easily enhance the visual appeal and expressiveness of documents. Manipulating shape elements is one of the highlights of Spire.Doc functionality, and this article will introduce you to how to add or delete shapes in Word using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Add Shapes in Word Document in Python

Spire.Doc for Python supports adding various shapes such as rectangles, trapezoids, triangles, arrows, lines, emoticons, and many other predefined shape types. By calling the Paragraph.AppendShape(width: float, height: float, shapeType: 'ShapeType') method, you can not only easily insert these shapes at any position in the document but also customize various properties of the shapes, such as fill color, border style, rotation angle, transparency, etc., to meet different typesetting needs and visual effects. Below are the detailed steps:

  • Create a new Document object.
  • Call Document.AddSection() and Section.AddParagraph() methods to add a section and a paragraph within the section, respectively.
  • Call the Paragraph.AppendShape(width: float, height: float, shapeType: 'ShapeType') method to add a shape on the paragraph, where width and height represent the dimensions of the shape, and shapeType enum is used to specify the type of shape.
  • Define the style of the shape, such as fill color, border color, border style, and width.
  • Set the horizontal and vertical position of the shape relative to the page.
  • Add multiple other types of shapes using the same method.
  • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a new Document object
doc = Document()

# Add a new section in the document
sec = doc.AddSection()

# Add a paragraph in the new section
para = sec.AddParagraph()

# Add a rectangle shape in the paragraph with width and height both 60
shape1 = para.AppendShape(60, 60, ShapeType.Rectangle)

# Define the fill color of the shape
shape1.FillColor = Color.get_YellowGreen()

# Define the border color
shape1.StrokeColor = Color.get_Gray()

# Define the border style and width
shape1.LineStyle = ShapeLineStyle.Single
shape1.StrokeWeight = 1

# Set the horizontal and vertical position of the shape relative to the page
shape1.HorizontalOrigin = HorizontalOrigin.Page
shape1.HorizontalPosition = 100
shape1.VerticalOrigin = VerticalOrigin.Page
shape1.VerticalPosition = 200

# Similarly, add a triangle shape in the same paragraph and set its properties
shape2 = para.AppendShape(60, 60, ShapeType.Triangle)
shape2.FillColor = Color.get_Green()
shape2.StrokeColor = Color.get_Gray()
shape2.LineStyle = ShapeLineStyle.Single
shape2.StrokeWeight = 1
shape2.HorizontalOrigin = HorizontalOrigin.Page
shape2.HorizontalPosition = 200
shape2.VerticalOrigin = VerticalOrigin.Page
shape2.VerticalPosition = 200

# Add an arrow shape and set its properties
shape3 = para.AppendShape(60, 60, ShapeType.Arrow)
shape3.FillColor = Color.get_SeaGreen()
shape3.StrokeColor = Color.get_Gray()
shape3.LineStyle = ShapeLineStyle.Single
shape3.StrokeWeight = 1
shape3.HorizontalOrigin = HorizontalOrigin.Page
shape3.HorizontalPosition = 300
shape3.VerticalOrigin = VerticalOrigin.Page
shape3.VerticalPosition = 200

# Add a smiley face shape and set its properties
shape4 = para.AppendShape(60, 60, ShapeType.SmileyFace)
shape4.FillColor = Color.get_LightGreen()
shape4.StrokeColor = Color.get_Gray()
shape4.LineStyle = ShapeLineStyle.Single
shape4.StrokeWeight = 1
shape4.HorizontalOrigin = HorizontalOrigin.Page
shape4.HorizontalPosition = 400
shape4.VerticalOrigin = VerticalOrigin.Page
shape4.VerticalPosition = 200

# Save the document
outputFile = "AddShapes.docx"
doc.SaveToFile(outputFile, FileFormat.Docx2016)

# Release the document
doc.Close()

Python: Add or Remove Shapes in Word

Add Shape Group in Word Document

Spire.Doc for Python not only provides the functionality to add individual shapes (such as rectangles, circles, lines, etc.) but also supports creating and managing grouped shapes. A grouped shape is a special collection of shapes that organizes multiple independent shapes together to form a whole, sharing the same transformation properties (such as position, rotation angle, etc.). Here are the specific steps to achieve this:

  • Create an object of the Document class.
  • Call the Document.AddSection() method to add a blank section.
  • Call the Section.AddParagraph() method to add a blank paragraph in the section.
  • Call Paragraph.AppendShapeGroup() to add a shape group and specify its dimensions.
  • Create a Textbox and specify its shape type, dimensions, position, fill color, and other properties.
  • Add paragraphs within the Textbox and insert text, setting the paragraph's horizontal alignment to center.
  • Add the Textbox to the list of child objects of the shape group.
  • Similar to the above steps, create shapes for symbols like arrows, diamond-shaped text boxes, octagonal text boxes, and set their properties, adding them to the list of child objects of the shape group.
  • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section to the document
sec = doc.AddSection()

# Add a paragraph to the section
para = sec.AddParagraph()

# Add a shape group to the paragraph and specify its horizontal position
shapegroup = para.AppendShapeGroup(375, 350)
shapegroup.HorizontalPosition = 180

# Calculate the relative unit scale X and Y for the shape group for subsequent element size positioning
X = float((shapegroup.Width / 1000.0))
Y = float((shapegroup.Height / 1000.0))

# Create a rounded rectangle text box
txtBox = TextBox(doc)

# Set the shape type of the text box
txtBox.SetShapeType(ShapeType.RoundRectangle)

# Set the width and height of the text box
txtBox.Width = 125 / X
txtBox.Height = 54 / Y

# Add a paragraph inside the text box and set its horizontal alignment to center
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# Add the text "Step One" to the paragraph
paragraph.AppendText("Step One")

# Set the horizontal and vertical position of the text box
txtBox.HorizontalPosition = 19 / X
txtBox.VerticalPosition = 27 / Y

# Set the fill color of the text box and remove the border line
txtBox.Format.FillColor = Color.FromRgb(153, 255, 255)
txtBox.Format.NoLine = True

# Add the text box to the list of child objects of the shape group
shapegroup.ChildObjects.Add(txtBox)

# Create a downward arrow shape and specify its shape type
arrowLineShape = ShapeObject(doc, ShapeType.DownArrow)

# Set the width and height of the arrow shape
arrowLineShape.Width = 16 / X
arrowLineShape.Height = 40 / Y

# Set the horizontal and vertical position of the arrow shape
arrowLineShape.HorizontalPosition = 73 / X
arrowLineShape.VerticalPosition = 87 / Y

# Set the stroke color of the arrow shape
arrowLineShape.StrokeColor = Color.get_CadetBlue()

# Add the arrow shape to the list of child objects of the shape group
shapegroup.ChildObjects.Add(arrowLineShape)

# (Similar subsequent code, creating diamond-shaped text boxes, downward arrow shapes, and octagonal text boxes, with corresponding property settings and positioning)

txtBox = TextBox(doc)
txtBox.SetShapeType(ShapeType.Diamond)
txtBox.Width = 125 / X
txtBox.Height = 54 / Y
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText("Step Two")
txtBox.HorizontalPosition = 19 / X
txtBox.VerticalPosition = 131 / Y
txtBox.Format.FillColor = Color.FromRgb(0, 102, 102)
txtBox.Format.NoLine = True
shapegroup.ChildObjects.Add(txtBox)

arrowLineShape = ShapeObject(doc, ShapeType.DownArrow)
arrowLineShape.Width = 16 / X
arrowLineShape.Height = 40 / Y
arrowLineShape.HorizontalPosition = 73 / X
arrowLineShape.VerticalPosition = 192 / Y
arrowLineShape.StrokeColor = Color.get_CadetBlue()
shapegroup.ChildObjects.Add(arrowLineShape)

txtBox = TextBox(doc)
txtBox.SetShapeType(ShapeType.Octagon)
txtBox.Width = 149 / X
txtBox.Height = 59 / Y
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText("Step Three")
txtBox.HorizontalPosition = 7 / X
txtBox.VerticalPosition = 236 / Y
txtBox.Format.FillColor = Color.FromRgb(51, 204, 204)
txtBox.Format.NoLine = True
shapegroup.ChildObjects.Add(txtBox)

# Define the output file name
outputFile = "ShapeGroup.docx"

# Save the document
doc.SaveToFile(outputFile, FileFormat.Docx2016)

# Close the document object
doc.Close()

Python: Add or Remove Shapes in Word

Remove Shapes from Word Document

Spire.Doc for Python supports efficiently removing individual shapes and shape groups from a Word document. Below are the detailed steps:

  • Create an object of the Document class.
  • Call the Document.LoadFromFile() method to load a document containing shapes.
  • Traverse through all the sections of the document and the body elements within the sections to get paragraphs.
  • Check if the child elements under the paragraph are shape objects or shape group objects.
  • Call the Paragraph.ChildObjects.Remove() method to remove the shape object.
  • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("ShapeGroup.docx")

# Iterate through all sections of the document
for s in range(doc.Sections.Count):    
    # Get the current section
    section = doc.Sections[s]
    
    # Iterate through all child objects within the section
    for i in range(section.Body.ChildObjects.Count):
        # Get the current child object
        document_object = section.Body.ChildObjects[i]
        
        # If the current child object is a paragraph
        if isinstance(document_object, Paragraph):
            # Convert the child object to a paragraph object
            paragraph = document_object
            
            # Initialize the inner loop index
            j = 0
            
            # Iterate through all child objects within the paragraph
            while j < paragraph.ChildObjects.Count:
                # Get the current child object within the paragraph
                c_obj = paragraph.ChildObjects[j]
                
                # If the current child object is a shape group or shape object
                if isinstance(c_obj, ShapeGroup) or isinstance(c_obj, ShapeObject):
                    # Remove the shape object from the paragraph
                    paragraph.ChildObjects.Remove(c_obj)
                    
                    # Update the inner loop index
                    j -= 1
                    
                # Increment the inner loop index
                j += 1

# Save the document
doc.SaveToFile("RemovedShapes.docx", FileFormat.Docx2016)

# Close the document object
doc.Close()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Mail merge is a powerful tool that allows users to efficiently create personalized documents for a large number of recipients. By using mail merge, users can streamline the document-creating process by automatically merging a template document with a data source, resulting in personalized and professional-looking documents that are tailored to each recipient, which is especially useful for tasks like sending out personalized emails, generating invoices, or creating customized marketing materials. This article demonstrates how to create and execute mail merge in Word documents with Spire.Doc for Python through Python code.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Create Mail Merge in Word Documents with Python

Mail merging in Word documents involves the utilization of mail merge fields. Spire.Doc for Python offers the Paragraph.AppendField(str: fieldName, FieldType.FieldMergeField) method, which allows users to efficiently create mail merge fields within a designated paragraph of a document. This feature enables users to easily generate a set of documents tailored to specific recipients by swiftly inputting personalized information at a later stage.

The detailed steps for creating mail merge fields in Word documents are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Get a section using Document.Sections.get_Item() method.
  • Get the paragraphs to insert mail merge fields using Section.Paragraphs.get_Item() method.
  • Append mail merge fields to the paragraphs using Paragraph.AppendField() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Get a section
section = doc.Sections.get_Item(1)

# Get the paragraphs to append the mail merge fields
para1 = section.Paragraphs.get_Item(0)
para2 = section.Paragraphs.get_Item(1)
para3 = section.Paragraphs.get_Item(2)
para4 = section.Paragraphs.get_Item(3)

# Append the mail merge fields and specify the field names
para1.AppendField("Name", FieldType.FieldMergeField)
para2.AppendField("Age", FieldType.FieldMergeField)
para3.AppendField("Phone Number", FieldType.FieldMergeField)
para4.AppendField("Membership Type", FieldType.FieldMergeField)

# Save the document
doc.SaveToFile("output/MailMergeFields.docx", FileFormat.Docx)
doc.Close()

Python: Create and Execute Mail Merge in Word Documents

Perform Mail Merge in Word Documents with Python

Once the mail merge has been created, the MailMerge.Execute(List: fieldNames, List: dataSource) method can be employed to execute the mail merge within the document. This enables the swift generation of multiple Word documents, each containing unique content as per the specified data source.

The detailed steps for performing mail merge and generate personalized documents are as follows:

  • Specify the data source
  • Loop through the data source:
    • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
    • Get the mail merge field names as a list using Document.MailMerge.GetMergeFieldNames() method.
    • Execute mail merge with specified data using Document.MailMerge.Execute() method.
    • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import Document

# Specify the data source
dataSource = member_data = [
    ["Alice Johnson", "35", "+1-555-123-4567", "Premium"],
    ["Bob Williams", "42", "+1-555-765-4321", "Standard"],
    ["Charlie Brown", "28", "+44-1234-567890", "Basic"],
]

# Loop through the data source
for i in range(len(dataSource)):
    # Create an instance of Document
    doc = Document()
    # Load a Word document with mail merge fields
    doc.LoadFromFile("output/MailMergeFields.docx")
    # Get the merge field names
    fieldNames = doc.MailMerge.GetMergeFieldNames()
    # Execute mail merge
    doc.MailMerge.Execute(fieldNames, dataSource[i])
    # Save the document
    doc.SaveToFile(f"output/Members/Member-{dataSource[i][0]}.docx")
doc.Close()

Python: Create and Execute Mail Merge in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Paragraph indentations determine the horizontal space between the page margins and the text of paragraphs. They are an important formatting tool used in various types of written documents, such as essays, reports, and articles, to improve readability and create a visual distinction between paragraphs. In this article, we will demonstrate how to set paragraph indentations in Word documents in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Set Paragraph Indentations in Word in Python

Microsoft Word provides four types of paragraph indent options that enable you to format your document efficiently. These options are as follows:

  • First Line Indent: The first line indent refers to the horizontal space between the left margin and the beginning of the first line of a paragraph. It indents only the first line while keeping the subsequent lines aligned with the left margin.
  • Left Indent: The left indent, also known as the paragraph indent or the left margin indent, determines the horizontal distance between the left margin and the entire paragraph. It uniformly indents the entire paragraph from the left margin.
  • Right Indent: The right indent sets the horizontal distance between the right margin and the entire paragraph. It indents the paragraph from the right side, shifting the text towards the left.
  • Hanging Indent: The hanging indent is a unique indentation style where the first line remains aligned with the left margin, while all subsequent lines of the paragraph are indented inward. This creates a "hanging" effect, commonly used for bibliographies, references, or citations.

Spire.Doc for Python supports all these types of indents. The table below lists some of the core classes and methods that are used to set different paragraph indents in Word with Spire.Doc for Python:

Name Description
ParagraphFormat Class Represents the format of a paragraph.
ParagraphFormat.SetLeftIndent() Method Sets the left indent value for paragraph.
ParagraphFormat.SetRightIndent() Method Sets the right indent value for paragraph.
ParagraphFormat.SetFirstLineIndent() Method Sets the first line or hanging indent value.  Positive value represents first-line indent, and negative value represents hanging indent.

The steps below explain how to set paragraph indents in a Word document using Spire.Doc for Python:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Get a specific section using Document.Sections[] property.
  • Get a specific paragraph using Section.Paragraphs[] property.
  • Get the paragraph format using Paragraph.Format property, and then set the paragraph indent using the above listed methods of ParagraphFormat class.
  • Save the document to another file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
doc = Document()
# Load a sample Word document
doc.LoadFromFile("Sample6.docx")

# Get the first section
section = doc.Sections[0]

# Get the first paragraph and set the left indent
para1 = section.Paragraphs[0]
para1.Format.SetLeftIndent(30)

# Get the second paragraph and set the right indent
para2 = section.Paragraphs[1]
para2.Format.SetRightIndent(30)

# Get the third paragraph and set the first line indent
para3 = section.Paragraphs[2]
para3.Format.SetFirstLineIndent(30)

# Get the fourth paragraph and set the hanging indent
para4 = section.Paragraphs[3]
para4.Format.SetFirstLineIndent(-30)

# Save the document to file
doc.SaveToFile("SetIndents.docx", FileFormat.Docx2013)
doc.Close()

Python: Set Paragraph Indentations in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Set different text alignment in Word with Python

In the world of document automation, proper text alignment is crucial for creating professional, readable, and visually appealing documents. For developers and data professionals building reports, drafting letters, or designing invoices, mastering text alignment in Python is essential to producing polished, consistent documents without manual editing.

This guide delivers a step-by-step walkthrough on how to align text in Python using Spire.Doc for Python, a library that enables effortless control over Word document formatting.


Why Choose Spire.Doc for Python to Align Text?​

Before diving into code, let’s clarify why Spire.Doc is a top choice for text alignment tasks:​

  • Full Alignment Support: Natively supports all standard alignment types (Left, Right, Center, Justify) for paragraphs.​
  • No Microsoft Word Dependency: Runs independently - no need to install Word on your machine.​
  • High Compatibility: Works with .docx, .doc, and other Word formats, ensuring your aligned documents open correctly across devices.​
  • Fine-Grained Control: Adjust alignment for entire paragraphs or table cells.​

Core Text Alignment Types in Spire.Doc​

Spire.Doc uses the HorizontalAlignment enum to define text alignment. The most common values are:​

  • HorizontalAlignment.Left: Aligns text to the left margin (default).​
  • HorizontalAlignment.Right: Aligns text to the right margin.​
  • HorizontalAlignment.Center: Centers text horizontally between margins.​
  • HorizontalAlignment.Justify: Adjusts text spacing so both left and right edges align with margins.​
  • HorizontalAlignment.Distribute: Adjusts character spacing (adds space between letters) and word spacing to fill the line.

Below, we’ll cover how to programmatically set paragraph alignment (left, right, center, justified, and distributed) in Word using Python


Step-by-Step: Align Text in Word in Python

Here are the actionable steps to generate a Word document with 5 paragraphs, each using a different alignment style.

Step 1: Install Spire.Doc for Python

Open your terminal/command prompt​, and then run the following command to install the latest version:

pip install Spire.Doc

Step 2: Import Required Modules

Import the core classes from Spire.Doc. These modules let you create documents, sections, paragraphs, and configure formatting:

from spire.doc import *
from spire.doc.common import *

Step 3: Create a New Word Document

Initialize a Document instance that represents your empty Word file:

# Create a Document instance
doc = Document()

Step 4: Add a Section to the Document

Word documents organize content into sections (each section can have its own margins, page size, etc.). We’ll add one section to hold our paragraphs:

# Add a section to the document
section = doc.AddSection()

Step 5: Add Paragraphs with Different Alignments

A section contains paragraphs, and each paragraph’s alignment is controlled via the HorizontalAlignment enum. We’ll create 5 paragraphs, one for each alignment type.

1. Left Align in Python

Left alignment is the default for most text (text aligns to the left margin).

# Left aligned text
paragraph1 = section.AddParagraph()
paragraph1.AppendText("This is left-aligned text.")
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Left

2. Right Align Text in Python

Right alignment is useful for dates, signatures, or page numbers (text aligns to the right margin).

# Right aligned text
paragraph2 = section.AddParagraph()
paragraph2.AppendText("This is right-aligned text.")
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Right

3. Center Text in Python

Center alignment works well for titles or headings (text centers between left and right margins). Use to center text in Python:

# Center aligned text
paragraph3 = section.AddParagraph()
paragraph3.AppendText("This is center-aligned text.")
paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center

4. Justify Text in Python

Justified text aligns both left and right margins (spaces between words are adjusted for consistency). Ideal for formal documents like essays or reports.

# Justified
paragraph4 = section.AddParagraph()
paragraph4.AppendText("This is justified text.")
paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Justify

Note: Justified alignment is more visible with longer text - short phrases may not show the spacing adjustment.

5. Distribute Text in Python

Distributed alignment is similar to justified, but evenly distributes single-line text (e.g., unevenly spaced words or short phrases).

# Distributed
Paragraph5 = section.AddParagraph()
Paragraph5.AppendText("This is evenly distributed text.")
Paragraph5.Format.HorizontalAlignment = HorizontalAlignment.Distribute

Step 6: Save and Close the Document

Finally, save the document to a specified path and close the Document instance to free resources:

# Save the document
document.SaveToFile("TextAlignment.docx", FileFormat.Docx2016)
# Close the document to release memory
document.Close()

Output:

Align paragraph text in Word in Python

Pro Tip: Spire.Doc for Python also provides interfaces to align tables in Word or align text in table cells.


FAQs About Python Text Alignment

Q1: Is Spire.Doc for Python free?

A: Spire.Doc offers a free version with limitations. For full functionality, you can request a 30-day trial license here.

Q2: Can I set text alignment for existing Word documents

A: Yes. Spire.Doc lets you load existing documents and modify text alignment for specific paragraphs. Here’s a quick example:

from spire.doc import *

# Load an existing document
doc = Document()
doc.LoadFromFile("ExistingDocument.docx")

# Get the first section and first paragraph
section = doc.Sections[0]
paragraph = section.Paragraphs[0]

# Change alignment to center
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# Save the modified document
doc.SaveToFile("UpdatedDocument.docx", FileFormat.Docx2016)
doc.Close()

Q3: Can I apply different alignments to different parts of the same paragraph?

A: No. Text alignment is a paragraph-level setting in Word, not a character-level setting. This means all text within a single paragraph must share the same alignment (left, right, center, etc.).

If you need mixed alignment in the same line, you’ll need to use a table with invisible borders.

Q4: Can Spire.Doc for Python handle other text formatting?

A: Absolutely! Spire.Doc lets you combine alignment with other formatting like fonts, line spacing, bullet points, and more.


Conclusion

Automating Word text alignment with Python and Spire.Doc saves time, reduces human error, and ensures consistency across documents. The code example provided offers a clear template for implementing left, right, center, justified, and distributed alignment, and adapting it to your needs is as simple as modifying the text or adding more formatting rules.

Try experimenting with different alignment combinations, and explore Spire.Doc’s online documentation to unlock more formatting possibilities.

Track changes in Microsoft Word is a powerful feature that facilitates document collaboration and review processes. When track changes is enabled, any modifications made to the document, such as text additions or deletions, formatting changes, and comments, are visually highlighted. This makes it easier for document editors or collaborators to identify and review the changes made by themselves or others. In this article, we will explain how to enable track changes, as well as accept or reject the tracked changes in Word documents in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Enable Track Changes in Word in Python

Spire.Doc for Python offers the Document.TrackChanges property to enable the track changes mode for a Word document. The detailed steps are as follows.

  • Create an object of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Enable the track changes mode for the document by setting the Document.TrackChanges property to True.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("Sample.docx")

# Enable the track changes mode for the document
doc.TrackChanges = True

# Save the result document
doc.SaveToFile("EnableTrackChanges.docx", FileFormat.Docx2016)
doc.Close()

Python: Enable Track Changes, Accept or Reject Tracked Changes in Word

Accept Tracked Changes in Word in Python

Accepting tracked changes allows you to incorporate the suggested modifications permanently into the document. By using the Document.AcceptChanges() method provided by Spire.Doc for Python, you can easily accept all tracked changes in a Word document. The detailed steps are as follows.

  • Create an object of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Check if the document has tracked changes using Document.HasChanges property.
  • Accept the tracked changes in the document using Document.AcceptChanges() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("Sample.docx")

# Check if the document has tracked changes
if(doc.HasChanges):
    # Accept the tracked changes in the document
    doc.AcceptChanges()

# Save the result document
doc.SaveToFile("AcceptChanges.docx", FileFormat.Docx2016)
doc.Close()

Python: Enable Track Changes, Accept or Reject Tracked Changes in Word

Reject Tracked Changes in Word in Python

Sometimes, suggested modifications may not align with your vision or requirements for the document. In such cases, rejecting these changes becomes essential to ensure that the document accurately reflects your intended content and formatting choices.

Spire.Doc for Python offers the Document.RejectChanges() method to reject the tracked changes in a Word document. The detailed steps are as follows.

  • Create an object of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Check if the document has tracked changes using Document.HasChanges property.
  • Reject the tracked changes in the document using Document.RejectChanges() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("Sample.docx")

# Check if the document has tracked changes
if(doc.HasChanges):
    # Reject the tracked changes in the document
    doc.RejectChanges()

# Save the result document
doc.SaveToFile("RejectChanges.docx", FileFormat.Docx2016)
doc.Close()

Python: Enable Track Changes, Accept or Reject Tracked Changes in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Python: Split Word Documents

2024-03-27 01:03:24 Written by Koohji

Efficiently managing Word documents often requires the task of splitting them into smaller sections. However, manually performing this task can be time-consuming and labor-intensive. Fortunately, Spire.Doc for Python provides a convenient and efficient way to programmatically segment Word documents, helping users to extract specific parts of a document, split lengthy documents into smaller chunks, and streamline data extraction. This article demonstrates how to use Spire.Doc for Python to split a Word document into multiple documents in Python.

The splitting of a Word document is typically done by page breaks and section breaks due to the dynamic nature of document content. Therefore, this article focuses on the following two parts:

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Split a Word Document by Page Breaks with Python

Page breaks allow for the forced pagination of a document, thereby achieving a fixed division of content. By using page breaks as divisions, we can split a Word document into smaller content-related documents. The detailed steps for splitting a Word document by page breaks are as follows:

  • Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
  • Create a new document, add a section to it using Document.AddSection() method.
  • Iterate through all body child objects in each section in the original document and check if the child object is a paragraph or a table.
  • If the child object is a table, add it to the section in the new document using Section.Body.ChildObjects.Add() method.
  • If the child object is a paragraph, add the paragraph object to the section in the new document. Then, iterate through all child objects of the paragraph and check if a child object is a page break.
  • If the child object in the paragraph is a page break, get its index using Paragraph.ChildObjects.IndexOf() method and remove it from the paragraph by its index.
  • Save the new document using Document.SaveToFile() method and repeat the above process.
  • Python
from spire.doc import *
from spire.doc.common import *

inputFile = "Sample.docx"
outputFolder = "output/SplitDocument/"

# Create an instance of Document
original = Document()
# Load a Word document
original.LoadFromFile(inputFile)

# Create a new word document and add a section to it
newWord = Document()
section = newWord.AddSection()
original.CloneDefaultStyleTo(newWord)
original.CloneThemesTo(newWord)
original.CloneCompatibilityTo(newWord)

index = 0
# Iterate through all sections of original document
for m in range(original.Sections.Count):
    sec = original.Sections.get_Item(m)
    # Iterate through all body child objects of each section
    for k in range(sec.Body.ChildObjects.Count):
        obj = sec.Body.ChildObjects.get_Item(k)
        if isinstance(obj, Paragraph):
            para = obj if isinstance(obj, Paragraph) else None
            sec.CloneSectionPropertiesTo(section)
            # Add paragraph object in original section into section of new document
            section.Body.ChildObjects.Add(para.Clone())
            for j in range(para.ChildObjects.Count):
                parobj = para.ChildObjects.get_Item(j)
                if isinstance(parobj, Break) and ( parobj if isinstance(parobj, Break) else None).BreakType == BreakType.PageBreak:
                    # Get the index of page break in paragraph
                    i = para.ChildObjects.IndexOf(parobj)
                    # Remove the page break from its paragraph
                    section.Body.LastParagraph.ChildObjects.RemoveAt(i)
                    # Save the new document
                    resultF = outputFolder
                    resultF += "SplitByPageBreak-{0}.docx".format(index)
                    newWord.SaveToFile(resultF, FileFormat.Docx)
                    index += 1
                    # Create a new document and add a section
                    newWord = Document()
                    section = newWord.AddSection()
                    original.CloneDefaultStyleTo(newWord)
                    original.CloneThemesTo(newWord)
                    original.CloneCompatibilityTo(newWord)
                    sec.CloneSectionPropertiesTo(section)
                    # Add paragraph object in original section into section of new document
                    section.Body.ChildObjects.Add(para.Clone())
                    if section.Paragraphs[0].ChildObjects.Count == 0:
                        # Remove the first blank paragraph
                        section.Body.ChildObjects.RemoveAt(0)
                    else:
                        # Remove the child objects before the page break
                        while i >= 0:
                            section.Paragraphs[0].ChildObjects.RemoveAt(i)
                            i -= 1
        if isinstance(obj, Table):
            # Add table object in original section into section of new document
            section.Body.ChildObjects.Add(obj.Clone())

# Save the document
result = outputFolder+"SplitByPageBreak-{0}.docx".format(index)
newWord.SaveToFile(result, FileFormat.Docx2013)
newWord.Close()

Python: Split Word Documents

Split a Word Document by Section Breaks with Python

Sections divide a Word document into different logical parts and allow for independent formatting for each section. By splitting a Word document into sections, we can obtain multiple documents with relatively independent content and formatting. The detailed steps for splitting a Word document by section breaks are as follows:

  • Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
  • Iterate through each section in the document.
  • Get a section using Document.Sections.get_Item() method.
  • Create a new Word document and copy the section in the original document to the new document using Document.Sections.Add() method.
  • Save the new document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Iterate through all sections
for i in range(document.Sections.Count):
    section = document.Sections.get_Item(i)
    result = "output/SplitDocument/" + "SplitBySectionBreak_{0}.docx".format(i+1)
    # Create a new Word document
    newWord = Document()
    # Add the section to the new document
    newWord.Sections.Add(section.Clone())
    #Save the new document
    newWord.SaveToFile(result)
    newWord.Close()

Python: Split Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Protecting valuable and sensitive information from unauthorized access is a crucial task for individuals and organizations alike. When it comes to sharing and storing confidential Word documents, such as financial records, legal documents, or personal records, encrypting the documents provides extra protection for their security and confidentiality. Moreover, using Python, users can easily encrypt large numbers of Word documents. This article shows how to use Spire.Doc for Python to encrypt Word documents in Python programs.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Encrypt a Word Document with a Password

Using the Document.Encrypt(password: str) method provided by Spire.Doc for Python, developers can set an open password for a Word document, ensuring that only authorized people can open and view the document. The detailed steps for encrypting a Word document with a password are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Encrypt the document using Document.Encrypt() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Encrypt the document
doc.Encrypt("password")

# Save the document
doc.SaveToFile("output/EncryptedDocument.docx")
doc.Close()

Python: Encrypt or Decrypt Word Documents

Change the Encryption from a Word Document

By passing the password as the parameter, developers can load an encrypted document using Document.LoadFromFile(fileName: str, fileFormat: FileFormat, password: str) method. After loading the encrypted document, the Document.Encrypt() method can be used to set a new password. The detailed steps are as follows:

  • Create an instance of Document class.
  • Load an encrypted Word document using Document.LoadFromFile() method.
  • Change the password of the document using Document.Encrypt() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load an encrypted Word document
doc.LoadFromFile("output/EncryptedDocument.docx", FileFormat.Docx, "password")

# Change the password
doc.Encrypt("password1")

# Save the document
doc.SaveToFile("output/ChangeDocument.docx")
doc.Close()

Remove the Password from a Word Document

After loading an encrypted Word document, developers can also use Document.RemoveEncryption() method to remove the encryption from the document directly, thus making the document available to all users. The detailed steps are as follows:

  • Create an instance of Document class.
  • Load an encrypted Word document using Document.LoadFromFile() method.
  • Remove the password using Document.RemoveEncryption() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load an encrypted Word document
doc.LoadFromFile("output/EncryptedDocument.docx", FileFormat.Auto, "password")

# Remove the password
doc.RemoveEncryption()

# Save the document
doc.SaveToFile("output/RemovePassword.docx", FileFormat.Docx)
doc.Close()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Paragraph spacing and line spacing are crucial formatting options in Microsoft Word that greatly influence the visual presentation and readability of your documents. Paragraph spacing determines the vertical space between paragraphs, creating a distinct separation between each paragraph. Line spacing, on the other hand, controls the vertical distance between lines within a paragraph, directly impacting the density and readability of the text. By appropriately setting paragraph spacing and line spacing, you can easily create visually appealing and easy-to-read documents. In this article, we will explain how to set paragraph spacing and line spacing in Word documents in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Set Paragraph Spacing in Word in Python

Spire.Doc for Python provides the Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties to adjust the spacing before and after a paragraph. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add two paragraphs to the section using Section.AddParagraph() methods.
  • Set the spacing before and after the paragraphs using Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section to the document
section = document.AddSection()

# Add two paragraphs to the section
para1 = section.AddParagraph()
para1.Format.HorizontalAlignment = HorizontalAlignment.Center
textRange1 = para1.AppendText("Spire.Doc for Python")
textRange1.CharacterFormat.TextColor = Color.get_Blue()
textRange1.CharacterFormat.FontName = "Calibri"
textRange1.CharacterFormat.FontSize = 15

para2 = section.AddParagraph()
textRange2 = para2.AppendText("Spire.Doc for Python is a professional Word Python API specifically designed for developers to create, read, write, convert, and compare Word documents with fast and high-quality performance.")
textRange2.CharacterFormat.FontName = "Calibri"
textRange2.CharacterFormat.FontSize = 12

# Set the spacing after the first paragraph
para1.Format.AfterAutoSpacing = False
para1.Format.AfterSpacing = 10

# Set the spacing before and after the second paragraph
para2.Format.BeforeAutoSpacing = False
para2.Format.BeforeSpacing = 10
para2.Format.AfterAutoSpacing = False
para2.Format.AfterSpacing = 10

# Save the result file
document.SaveToFile("SetParagraphSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing in Word

Set Line Spacing in Word in Python

To set the pacing between lines in a paragraph, you can use the Paragraph.Format.LineSpacing property. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() methods.
  • Set the spacing between lines in the paragraph using Paragraph.Format.LineSpacing property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section
section = document.AddSection()

# Add a paragraph to the section
para = section.AddParagraph()
textRange = para.AppendText("Spire.Doc for Python is a proven reliable MS Word API for Python which enables to perform many Word document processing tasks. Spire.Doc for Python supports Word 97-2003 /2007/2010/2013/2016/2019 and it has the ability to convert them to commonly used file formats like XML, RTF, TXT, XPS, EPUB, EMF, HTML and vice versa. Furthermore, it supports to convert Word Doc/Docx to PDF using Python, Word to SVG, and Word to PostScript in high quality.")
textRange.CharacterFormat.FontName = "Calibri"
textRange.CharacterFormat.FontSize = 12

# Set line spacing rule
para.Format.LineSpacingRule = LineSpacingRule.Multiple
# Set line spacing value (The line spacing rule "Multiple" with value 18 sets the line spacing to "1.5 lines", value 12 sets the line spacing to "Single")
para.Format.LineSpacing = 18

# Save the result file
document.SaveToFile("SetLineSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Comparing two Word documents for differences is a crucial task when reviewing changes, ensuring accuracy, and collaborating on content. This process allows you to identify additions, deletions, and modifications made between different document iterations. By comparing versions, you can efficiently track alterations, verify updates, and maintain document integrity. In this article, you will learn how to compare two versions of a Word document in Python using the Spire.Doc for Python library.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Compare Two Versions of a Word Document in Python

MS Word also offers a "Compare" feature that allows you to directly compare two versions of a document. This feature generates a new document that highlights the differences between the two versions.

To achieve similar results using Spire.Doc for Python, load the original and revised versions into two separate Document objects. Then, use the Compare() method to compare the revised version against the original. Finally, save the comparative document, which highlights the alterations, using the SaveToFile() method.

The steps to compare two version of a Word document using Python are as follows.

  • Load the first document (original version) while initializing the Document object.
  • Load the second document (revised version) while initializing the Document object.
  • Call Compare() method of the first Document object to compare the revised version against the original version.
  • Save the comparison results in a new Word document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Load the first document while initializing the Document object
firstDoc = Document("C:\\Users\\Administrator\\Desktop\\Original.docx")

# Load the second document while initializing the Document object
secondDoc = Document("C:\\Users\\Administrator\\Desktop\\Revised.docx")

# Compare two documents
firstDoc.Compare(secondDoc, "E-ICEBLUE")

# Save the comparison results in a new document
firstDoc.SaveToFile("Output/Differences.docx", FileFormat.Docx2016)

# Dispose resources
firstDoc.Dispose()
secondDoc.Dispose()

Python: Compare Two Versions of a Word Document

Compare Two Versions of a Word Document While Ignoring Formatting in Python

Comparing two versions of a Word document while ignoring formatting can be useful when you want to focus solely on the textual changes and disregard any formatting modifications.

To customize the comparison options in Spire.Doc for Python, use the CompareOptions class. If you want to exclude formatting from the comparison process, you can set the IgnoreFormatting property of the CompareOptions object to True. When you call the Compare() method, simply pass the CompareOptions object as an argument to achieve the desired comparison behavior.

The following are the steps to compare two versions of a Word document while ignoring formatting using Python.

  • Load the first document (original version) while initializing the Document object.
  • Load the second document (revised version) while initializing the Document object.
  • Create a CompareOptions object and set its IgnoreFormatting property to True.
  • Call Compare() method of the first Document object, passing the CompareOptions object as a parameter, to compare the revision against the original while ignoring formatting.
  • Save the comparison results in a new Word document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Load the first document while initializing the Document object
firstDoc = Document("C:\\Users\\Administrator\\Desktop\\Original.docx")

# Load the second document while initializing the Document object
secondDoc = Document("C:\\Users\\Administrator\\Desktop\\Revised.docx")

# Set compare option to ignore formatting changes
compareOptions = CompareOptions()
compareOptions.IgnoreFormatting = True

# Compare the two Word documents with options
firstDoc.Compare(secondDoc, "E-ICEBLUE", compareOptions)

# Save the comparison results in a new document
firstDoc.SaveToFile("Output/DifferencesWithoutFormattingChanges.docx", FileFormat.Docx2016)

# Dispose resources
firstDoc.Dispose()
secondDoc.Dispose()

Python: Compare Two Versions of a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Efficient document organization and navigability are crucial for lengthy Word documents. One powerful way to streamline document readability and accessibility is by incorporating a table of contents (TOC) into a Word document, which allows readers to quickly locate specific sections and jump to relevant content. By harnessing the capabilities of Python, users can effortlessly generate a table of contents that dynamically updates as the document evolves. This article provides a step-by-step guide and code examples for inserting a table of contents into a Word document in Python programs using Spire.Doc for Python, empowering users to create professional-looking documents with ease.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Insert the Default Table of Contents into a Word Document

Spire.Doc for Python supports inserting a table of contents in a Word document based on the headings of different levels. If the document does not have heading levels set, developers can set the heading levels using the Paragraph.ApplyStyle(BuiltinStyle) method before inserting a table of contents.

By using the Paragraph.AppendTOC(lowerLevel: int, upperLevel: int) method, developers can insert a table of contents at any paragraph and specify the titles to be displayed. It is important to note that after inserting the table of contents, developers need to use the Document.UpdateTableOfContents() method to update the table of contents so that its contents are displayed correctly.

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Add a section using Document.AddSection() method, add a paragraph to the section using Section.AddParagraph() method, and insert the new section after the cover section using Document.Sections.Insert(index: int, entity: Section) method.
  • Update the table of contents using Document.UpdateTableOfContents() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Create a section for the table of contents
section = doc.AddSection()

# Add a paragraph in the section
paragraph = section.AddParagraph()

# Append a table of contents in the paragraph
paragraph.AppendTOC(1, 2)

# Insert the section after the cover section
doc.Sections.Insert(1, section)

# Update the table of contents
doc.UpdateTableOfContents()

# Save the document
doc.SaveToFile("output/DefaultTOC.docx")
doc.Close()

Python: Insert a Table of Contents into a Word Document

Insert a Custom Table of Contents into a Word Document

Developers can also create a table of contents by initializing a TableOfContent object, and customize it through switches. For example, the switch "{\\o \"1-2\" \\n 1-1}" indicates showing headings from level one to level three in the table of contents and omitting the page numbers of level one headings. The detailed steps for inserting a customized table of contents into a Word document are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Add a section to the document using Document.AddSecction() method, add a paragraph to the section using Section.AddParagraph() method, and insert the section after the cover section using Document.Sections.Insert() method.
  • Create an object of TableOfContents class and insert it into the added paragraph using Paragraph.Items.Add() method.
  • Append field separator and field end mark to end the TOC filed using Paragraph.AppendFieldMark() method.
  • Set the created table of contents as the table of contents of the document through Document.TOC property.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")

# Add a section and a paragraph and insert the section after the cover section
section = doc.AddSection()
paragraph = section.AddParagraph()
doc.Sections.Insert(1, section)

# Customize a table of contents with switches
toc = TableOfContent(doc, "{\\o \"1-2\" \\n 1-1}")

# Insert the TOC to the paragraph
paragraph.Items.Add(toc)

# Insert field separator and filed end mark to end the TOC field
paragraph.AppendFieldMark(FieldMarkType.FieldSeparator)
paragraph.AppendFieldMark(FieldMarkType.FieldEnd)

# Set the TOC field as the table of contents of the document
doc.TOC = toc

# Update the TOC
doc.UpdateTableOfContents()

# Save the document
doc.SaveToFile("output/CustomizedTOC.docx")
doc.Close()

Python: Insert a Table of Contents into a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 4 of 7
page 4