Python (355)
Python: Create, Modify, and Copy Slide Master in PowerPoint Presentations
2024-05-13 01:14:23 Written by KoohjiSlide Master in PowerPoint presentations is a powerful feature that lies at the heart of designing consistent and professional-looking slideshows. It's essentially a blueprint or a template that controls the overall design and layout of the slides, allowing users to establish uniformity across presentations without having to manually format each slide individually. In this article, we will explore how to harness the power of Spire.Presentation for Python to create, modify, and apply slide masters in PowerPoint presentations within Python programs.
- Create and Apply Slide Masters in PowerPoint Presentations
- Modify Slide Masters in PowerPoint Presentations
- Copy Slide Masters Between PowerPoint Presentations
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Presentation
If you are unsure how to install, please refer to: How to Install Spire.Presentation for Python on Windows
Create and Apply Slide Masters in PowerPoint Presentations
Every PowerPoint presentation in PowerPoint, regardless of whether it is newly created or not, will have at least one slide master. Developers can modify the default master or create new ones and apply them to slides with Spire.Presentation for Python to achieve a consistent style and content layout across the presentation.
The detailed steps for creating new slide masters and applying them to the slides in a presentation file are as follows:
- Create an object of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Create slide masters using Presentation.Masters.AppendSlide() method.
- Use the methods under IMasterSlide class to set the backgrounds, customize color schemes, insert images, shapes, and text, etc.
- Apply the slide masters to specific slides through ISlide.Layout property.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create an instance of Presentation class
pres = Presentation()
# Load a Presentation file
pres.LoadFromFile("Sample.pptx")
# Add a cover slide master and a body slide master
master1 = pres.Masters.AppendSlide(pres.Masters.get_Item(0))
coverMaster = pres.Masters.get_Item(master1)
master2 = pres.Masters.AppendSlide(pres.Masters.get_Item(0))
bodyMaster = pres.Masters.get_Item(master2)
# Set background images for the two slide masters
pic1 = "Background1.jpg"
pic2 = "Background2.jpg"
rect = RectangleF.FromLTRB (0, 0, pres.SlideSize.Size.Width, pres.SlideSize.Size.Height)
coverMaster.SlideBackground.Fill.FillType = FillFormatType.Picture
image1 = coverMaster.Shapes.AppendEmbedImageByPath (ShapeType.Rectangle, pic1, rect)
coverMaster.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image1.PictureFill.Picture.EmbedImage
bodyMaster.SlideBackground.Fill.FillType = FillFormatType.Picture
image2 = bodyMaster.Shapes.AppendEmbedImageByPath (ShapeType.Rectangle, pic2, rect)
bodyMaster.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image2.PictureFill.Picture.EmbedImage
# Insert a logo to the body slide master
logo = "Logo.png"
bodyMaster.Shapes.AppendEmbedImageByPath(ShapeType.Rectangle, logo, RectangleF.FromLTRB(pres.SlideSize.Size.Width - 110, 10, pres.SlideSize.Size.Width - 10, 110))
# Insert text to the body slide master
shape = bodyMaster.Shapes.AppendShape(ShapeType.Rectangle, RectangleF.FromLTRB(pres.SlideSize.Size.Width - 210, 110, pres.SlideSize.Size.Width - 10, 150))
shape.Fill.FillType = FillFormatType.none
shape.Line.FillType = FillFormatType.none
shape.TextFrame.Text = "Spire.Presentation"
# Set the color scheme for the two slide masters
coverMaster.Theme.ColorScheme.Accent1.Color = Color.get_Red()
coverMaster.Theme.ColorScheme.Accent2.Color = Color.get_Blue()
bodyMaster.Theme.ColorScheme.Accent1.Color = Color.get_Brown()
coverMaster.Theme.ColorScheme.Accent2.Color = Color.get_Green()
# Apply the first master with layout to the first slide
pres.Slides.get_Item(0).Layout = coverMaster.Layouts.GetByType(SlideLayoutType.Title)
# Apply the second master with layout to other slides
for i in range(1, pres.Slides.Count):
pres.Slides.get_Item(i).Layout = bodyMaster.Layouts.GetByType(SlideLayoutType.TitleAndObject)
# Save the document
pres.SaveToFile("output/CreateAndApplySlideMaster.pptx", FileFormat.Pptx2016)
pres.Dispose()

Modify Slide Masters in PowerPoint Presentations
A presentation can have multiple slide masters, which can be applied to different slides to achieve a unified style application and modification for different types of slides.
The Presentation.Masters.get_Item() method in Spire.Presentation for Python allows developers to retrieve the specified slide master in the presentation by index and modify the master. The following step-by-step example demonstrates how to retrieve a slide master and modify its background, color scheme, and embedded images:
- Create an object of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a slide master through Presentation.Masters property.
- Use the methods under IMasterSlide class to change the background, set the color scheme, delete and insert text and images, etc.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create an object of Presentation
pres = Presentation()
# Load a PowerPoint presentation
pres.LoadFromFile("output/CreateAndApplySlideMaster.pptx")
# Get the third slide master
master = pres.Masters[2]
# Change the background
master.SlideBackground.Type = BackgroundType.Custom
master.SlideBackground.Fill.FillType = FillFormatType.Solid
master.SlideBackground.Fill.SolidColor.Color = Color.get_LightBlue()
# Change the color sheme
master.Theme.ColorScheme.Accent1.Color = Color.get_Red()
master.Theme.ColorScheme.Accent2.Color = Color.get_Green()
# Remove the pictures in the slide master
pictures = [shape for shape in master.Shapes if isinstance(shape, SlidePicture)]
for picture in pictures:
master.Shapes.Remove(picture)
# Change the text in the slide master
texts = [shape for shape in master.Shapes if isinstance(shape, IAutoShape)]
for text in texts:
if len(text.TextFrame.Text) != 0:
text.TextFrame.Text = "Spire.Presentation for Python"
# Save the presentation
pres.SaveToFile("output/ModifySlideMaster.pptx", FileFormat.Pptx2016)
pres.Dispose()

Copy Slide Masters Between PowerPoint Presentations
Applying the slide style of a presentation to another presentation can be achieved by copying the slide master between presentations and applying the master style to the specified slides. The following are the steps to copy the slide master between presentations and apply it to the specified slides:
- Create two objects of Presentation class and load two presentation documents using Presentation.LoadFromFile() method.
- Get the slide master of the second presentation using Presentation.Masters.get_Item() method.
- Add the slide master to the first presentation using Presentation.Masters.AppendSlide() method.
- Apply the slide master to the slides in the second presentation through ISlide.Layout property.
- Save the first presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import *
from spire.presentation.common import *
# Create two objects of Presentation
pres1 = Presentation()
pres2 = Presentation()
# Load two PowerPoint documents
pres1.LoadFromFile("Sample.pptx")
pres2.LoadFromFile("Template.pptx")
# Get the slide master of the second presentation
master = pres2.Masters.get_Item(0)
# Add the slide master to the first presentation
index = pres1.Masters.AppendSlide(master)
# Apply the slide master to the first presentation
pres1.Slides.get_Item(0).Layout = pres1.Masters.get_Item(index).Layouts.GetByType(SlideLayoutType.Title)
for i in range(1, pres1.Slides.Count):
pres1.Slides.get_Item(i).Layout = pres1.Masters.get_Item(index).Layouts.GetByType(SlideLayoutType.TitleAndObject)
# Save the first presentation
pres1.SaveToFile("output/CopySlideMaster.pptx", FileFormat.Pptx2013)
pres1.Dispose()
pres2.Dispose()

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.
TIFF is a popular image format used in scanning and archiving due to its high quality and support for a wide range of color spaces. On the other hand, PDFs are widely used for document exchange because they preserve the layout and formatting of a document while compressing the file size. Conversion between these formats can be useful for various purposes such as archival, editing, or sharing documents.
In this article, you will learn how to convert PDF to TIFF and TIFF to PDF using the Spire.PDF for Python and Pillow libraries.
Install Spire.PDF for Python
This situation relies on the combination of Spire.PDF for Python and Pillow (PIL). Spire.PDF is used to read, create and convert PDF documents, while the PIL library is used for handling TIFF files and accessing their frames.
The libraries can be easily installed on your device through the following pip command.
pip install Spire.PDF pip install pillow
Convert PDF to TIFF in Python
To complete the PDF to TIFF conversion, you first need to load the PDF document and convert the individual pages into image streams using Spire.PDF. Subsequently, these image streams are then merged together using the functionality of the PIL library, resulting in a consolidated TIFF image.
The following are the steps to convert PDF to TIFF using Python.
- Create a PdfDocument object.
- Load a PDF document from a specified file path.
- Iterate through the pages in the document.
- Convert each page into an image stream using PdfDocument.SaveAsImage() method.
- Convert the image stream into a PIL image.
- Combine these PIL images into a single TIFF image.
- Python
from spire.pdf.common import *
from spire.pdf import *
from PIL import Image
from io import BytesIO
# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")
# Create an empty list to store PIL Images
images = []
# Iterate through all pages in the document
for i in range(doc.Pages.Count):
# Convert a specific page to an image stream
with doc.SaveAsImage(i) as imageData:
# Open the image stream as a PIL image
img = Image.open(BytesIO(imageData.ToArray()))
# Append the PIL image to list
images.append(img)
# Save the PIL Images as a multi-page TIFF file
images[0].save("Output/ToTIFF.tiff", save_all=True, append_images=images[1:])
# Dispose resources
doc.Dispose()

Convert TIFF to PDF in Python
With the assistance of the PIL library, you can load a TIFF file and transform each frame into distinct PNG files. Afterwards, you can utilize Spire.PDF to draw these PNG files onto pages within a PDF document.
To convert a TIFF image to a PDF document using Python, follow these steps.
- Create a PdfDocument object.
- Load a TIFF image.
- Iterate though the frames in the TIFF image.
- Get a specific frame, and save it as a PNG file.
- Add a page to the PDF document.
- Draw the image on the page at the specified location using PdfPageBase.Canvas.DrawImage() method.
- Save the document to a PDF file.
- Python
from spire.pdf.common import *
from spire.pdf import *
from PIL import Image
import io
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a TIFF image
tiff_image = Image.open("C:\\Users\\Administrator\\Desktop\\TIFF.tiff")
# Go to the current frame
tiff_image.seek(i)
# Extract the image of the current frame
frame_image = tiff_image.copy()
# Save the image to a PNG file
frame_image.save(f"temp/output_frame_{i}.png")
# Load the image file to PdfImage
image = PdfImage.FromFile(f"temp/output_frame_{i}.png")
# Get image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page to the document
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save the document to a PDF file
doc.SaveToFile("Output/TiffToPdf.pdf",FileFormat.PDF)
# Dispose resources
doc.Dispose()

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.
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()

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()

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.get_Item(i)
# 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.get_Item(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.get_Item(i)
# 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.
In Microsoft Excel, text alignment and text orientation are crucial formatting options for optimizing the presentation of text within cells. Text alignment determines the horizontal or vertical positioning of text within a cell, while text orientation controls the tilt angle or display direction of the text. By flexibly utilizing these formatting options, you can customize the appearance of text within cells to create professional and visually appealing spreadsheets. In this article, we will demonstrate how to set text alignment and orientation in Excel in Python using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Set Text Alignment and Orientation in Excel in Python
Spire.XLS for Python provides the CellRange.Style.HorizontalAlignment and CellRange.Style.VerticalAlignment properties that enable you to customize the horizontal and vertical alignment of text in a single cell or range of cells. Additionally, it allows you to change the orientation of text by applying rotation to cells using the CellRange.Style.Rotation property. The detailed steps are as follows:
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet using the Workbook.Worksheets[index] property.
- Set the horizontal alignment for text in specific cells to Left, Center, Right, or General using the CellRange.Style.HorizontalAlignment property.
- Set the vertical alignment for text in specific cells to Top, Center, or Bottom using the CellRange.Style.VerticalAlignment property.
- Change the orientation for text in specific cells using the CellRange.Style.Rotation property.
- Save the result file using the Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create an object of the Workbook class
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Example.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Set the horizontal alignment for text in a specific cell to Left
sheet.Range["B1"].Style.HorizontalAlignment = HorizontalAlignType.Left
# Set the horizontal alignment for text in a specific cell to Center
sheet.Range["B2"].Style.HorizontalAlignment = HorizontalAlignType.Center
# Set the horizontal alignment for text in a specific cell to Right
sheet.Range["B3"].Style.HorizontalAlignment = HorizontalAlignType.Right
# Set the horizontal alignment for text in a specific cell to General
sheet.Range["B4"].Style.HorizontalAlignment = HorizontalAlignType.General
# Set the vertical alignment for text in a specific cell to Top
sheet.Range["B5"].Style.VerticalAlignment = VerticalAlignType.Top
# Set the vertical alignment for text in a specific cell to Center
sheet.Range["B6"].Style.VerticalAlignment = VerticalAlignType.Center
# Set the vertical alignment for text in a specific cell to Bottom
sheet.Range["B7"].Style.VerticalAlignment = VerticalAlignType.Bottom
# Change the text orientation in specific cells by applying rotation
sheet.Range["B8"].Style.Rotation = 45
sheet.Range["B9"].Style.Rotation = 90
# Save the result file
workbook.SaveToFile("TextAlignmentAndOrientation.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

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.
Spire.XLS for Python is a high-performance library for reading and writing Excel spreadsheets in Python. With Spire.XLS, you can create, read, edit, and convert XLS and XLSX files without the need for Microsoft Excel to be installed on your system.
This article demonstrates how to install Spire.XLS for Python on Mac.
Step 1
Download the most recent version of Python for macOS and install it on your Mac. If you have already completed this step, proceed directly to step 2.

Step 2
Open VS Code and search for 'Python' in the Extensions panel. Click 'Install' to add support for Python in your VS Code.

Step 3
Click 'Explorer' > 'NO FOLRDER OPENED' > 'Open Folder'.

Choose an existing folder as the workspace, or you can create a new folder and then open it.

Add a .py file to the folder you just opened and name it whatever you want (in this case, HelloWorld.py).

Step 4
Use the keyboard shortcut Ctrl + ` to open the Terminal. Then, install Spire.XLS for Python by entering the following command line in the terminal.
pip3 install spire.xls
Note that pip3 is a package installer specifically designed for Python 3.x versions, while pip is a package installer for Python 2.x versions. If you are working with Python 2.x, you can use the pip command.

Step 5
Open a Terminal window on your Mac, and type the following command to obtain the installation path of Python on your system.
python3 -m pip --version

Step 6
Add the following code snippet to the 'HelloWorld.py' file.
- Python
from spire.xls.common import *
from spire.xls import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Range["A1"].Text = "Hello World"
sheet.Range["A1"].AutoFitColumns()
workbook.SaveToFile("HelloWorld.xlsx", ExcelVersion.Version2010)
workbook.Dispose()

After executing the Python file, you will find the resulting Excel document displayed in the 'EXPLORER' panel.

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()

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()

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.get_Item(0)
# Get the first paragraph and set the left indent
para1 = section.Paragraphs.get_Item(0)
para1.Format.SetLeftIndent(30)
# Get the second paragraph and set the right indent
para2 = section.Paragraphs.get_Item(1)
para2.Format.SetRightIndent(30)
# Get the third paragraph and set the first line indent
para3 = section.Paragraphs.get_Item(2)
para3.Format.SetFirstLineIndent(30)
# Get the fourth paragraph and set the hanging indent
para4 = section.Paragraphs.get_Item(3)
para4.Format.SetFirstLineIndent(-30)
# Save the document to file
doc.SaveToFile(""SetIndents.docx"", FileFormat.Docx2013)
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.
Python: Add, Modify, or Remove Footers from PowerPoint Documents
2024-04-18 01:08:25 Written by KoohjiIn a PowerPoint document, the footer is an area located at the bottom of each slide, typically containing textual information such as page numbers, dates, authors, and more. By adding a footer, you can give your slides a professional look and provide important information. Modifying the footer allows you to adjust the displayed content, style, and position to meet specific needs or styles. Removing the footer can clear the bottom content when extra information is not needed or to maintain a clean appearance. This article will introduce how to use Spire.Presentation for Python to add, modify, or remove footers in PowerPoint documents within a Python project.
- Python Add Footers in PowerPoint Documents
- Python Modify Footers in PowerPoint Documents
- Python Remove Footers in PowerPoint Documents
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Python Add Footers in PowerPoint Documents
Using Spire.Presentation, you can add footers, page numbers, and time information to the bottom of each page in a PowerPoint document, ensuring consistent footer content across all pages. Here are the detailed steps:
- Create a Presentation object.
- Load a PowerPoint document using the Presentation.LoadFromFile() method.
- Set the footer visible using Presentation.FooterVisible = true and set the footer text.
- Set the slide number visible using Presentation.SlideNumberVisible = true, iterate through each slide, check for the lisence of a page number placeholder, and modify the text to the "Page X" format if found.
- Set the date visible using Presentation.DateTimeVisible = true.
- Set the format of the date using the Presentation.SetDateTime() method.
- Save the document using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Load the presentation from a file
presentation.LoadFromFile("Sample1.pptx")
# Set the footer visible
presentation.FooterVisible = True
# Set the footer text to "Spire.Presentation"
presentation.SetFooterText("Spire.Presentation")
# Set the slide number visible
presentation.SlideNumberVisible = True
# Iterate through each slide in the presentation
for slide in presentation.Slides:
for shape in slide.Shapes:
if shape.IsPlaceholder:
# If it is a slide number placeholder
if shape.Placeholder.Type == PlaceholderType.SlideNumber:
autoShape = shape if isinstance(shape, IAutoShape) else None
if autoShape is not None:
text = autoShape.TextFrame.TextRange.Paragraph.Text
# Modify the slide number text to "Page X"
autoShape.TextFrame.TextRange.Paragraph.Text = "Page " + text
# Set the date and time visible
presentation.DateTimeVisible = True
# Set the date and time format
presentation.SetDateTime(DateTime.get_Now(), "MM/dd/yyyy")
# Save the modified presentation to a file
presentation.SaveToFile("AddFooter.pptx", FileFormat.Pptx2016)
# Dispose of the Presentation object resources
presentation.Dispose()

Python Modify Footers in PowerPoint Documents
To modify the footer in a PowerPoint document, you first need to inspect the elements of each slide to locate footer and page number placeholders. Then, for each type of placeholder, set the desired content and format to ensure consistent and compliant footers throughout the document. Here are the detailed steps:
- Create a Presentation object.
- Load a PowerPoint document using the Presentation.LoadFromFile() method.
- Use the Presentation.Slides[index] property to retrieve a slide.
- Iterate through the shapes in the slide using a for loop, check each shape to determine if it is a placeholder such as a footer or page number placeholder, and then modify its content or format accordingly.
- Save the document using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
def change_font(paragraph):
for textRange in paragraph.TextRanges:
# Set the text style to italic
textRange.IsItalic = TriState.TTrue
# Set the text font
textRange.EastAsianFont = TextFont("Times New Roman")
# Set the text font size to 12
textRange.FontHeight = 34
# Set the text color
textRange.Fill.FillType = FillFormatType.Solid
textRange.Fill.SolidColor.Color = Color.get_SkyBlue()
# Create a Presentation object
presentation = Presentation()
# Load a presentation from a file
presentation.LoadFromFile("Sample2.pptx")
# Get the first slide
slide = presentation.Slides[0]
# Iterate through the shapes on the slide
for shape in slide.Shapes:
# Check if the shape is a placeholder
if shape.Placeholder is not None:
# Get the placeholder type
type = shape.Placeholder.Type
# If it is a footer placeholder
if type == PlaceholderType.Footer:
# Convert the shape to IAutoShape type
autoShape = shape if isinstance(shape, IAutoShape) else None
if autoShape is not None:
# Set the text content to "E-ICEBLUE"
autoShape.TextFrame.Text = "E-ICEBLUE"
# Modify the text font
change_font(autoShape.TextFrame.Paragraphs[0])
# If it is a slide number placeholder
if type == PlaceholderType.SlideNumber:
# Convert the shape to IAutoShape type
autoShape = shape if isinstance(shape, IAutoShape) else None
if autoShape is not None:
# Modify the text font
change_font(autoShape.TextFrame.Paragraphs[0])
# Save the modified presentation to a file
presentation.SaveToFile("ModifiedFooter.pptx", FileFormat.Pptx2016)
# Release the resources of the Presentation object
presentation.Dispose()

Python Remove Footers in PowerPoint Documents
To delete footers in a PowerPoint document, you first need to locate placeholders such as footers, page numbers, and time in the slides, and then remove them from the collection of shapes in the slide to ensure complete removal of footer content. Here are the detailed steps:
- Create a Presentation object.
- Load a PowerPoint document using the Presentation.LoadFromFile() method.
- Use the Presentation.Slides[index] property to retrieve a slide.
- Iterate through the shapes in the slide using a for loop, check if they are placeholders, and if they are footer placeholders, page number placeholders, or time placeholders, remove them from the slide.
- Save the document using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Load a presentation from a file
presentation.LoadFromFile("Sample2.pptx")
# Get the first slide
slide = presentation.Slides[0]
# Iterate through the shapes on the slide
for i in range(len(slide.Shapes) - 1, -1, -1):
# Check if the shape is a placeholder
if slide.Shapes[i].Placeholder is not None:
# Get the placeholder type
type = slide.Shapes[i].Placeholder.Type
# If it is a footer placeholder
if type == PlaceholderType.Footer:
# Remove it from the slide
slide.Shapes.RemoveAt(i)
# If it is a slide number placeholder
if type == PlaceholderType.SlideNumber:
# Remove it from the slide
slide.Shapes.RemoveAt(i)
# If it is a date and time placeholder
if type == PlaceholderType.DateAndTime:
# Remove it from the slide
slide.Shapes.RemoveAt(i)
# Save the modified presentation to a file
presentation.SaveToFile("RemovedFooter.pptx", FileFormat.Pptx2016)
# Release the resources of the Presentation object
presentation.Dispose()

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.
The AutoFit feature in Microsoft Excel is a handy tool that allows you to automatically adjust the height of rows or the width of columns in an Excel spreadsheet to fit the content within them. This feature is particularly useful when you have data that may vary in length or when you want to ensure that all the content is visible without having to manually adjust the column widths or row heights. In this article, we will explain how to AutoFit rows and columns in Excel in Python using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
AutoFit a Specific Row and Column in Python
To AutoFit a specific row and column in an Excel worksheet, you can use the Worksheet.AutoFitRow() and Worksheet.AutoFitColumn() methods. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- AutoFit a specific row and column in the worksheet by its index (1-based) using Worksheet.AutoFitRow(rowIndex) and Worksheet.AutoFitColumn(columnIndex) methods.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create an object of the Workbook class
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Automatically adjust the height of the 3rd row in the worksheet
sheet.AutoFitRow(3)
# Automatically adjust the width of the 4th column in the worksheet
sheet.AutoFitColumn(4)
# Save the resulting file
workbook.SaveToFile("AutoFitSpecificRowAndColumn.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

AutoFit Multiple Rows and Columns in Excel in Python
To AutoFit multiple rows and columns within a cell range, you can use the CellRange.AutoFitRows() and CellRange.AutoFitColumns() methods. The following are the detailed steps.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFroFmFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Get a specific cell range in the worksheet using Worksheet.Range[] property.
- AutoFit the rows and columns in the cell range using CellRange.AutoFitRows() and CellRange.AutoFitColumns() methods.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create an object of the Workbook class
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Get a specific cell range in the worksheet
range = sheet.Range["A1:E14"]
# Or get the used cell range in the worksheet
# range = sheet.AllocatedRange
# Automatically adjust the heights of all rows in the cell range
range.AutoFitRows()
# Automatically adjust the widths of all columns in the cell range
range.AutoFitColumns()
# Save the resulting file
workbook.SaveToFile("AutoFitMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
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.
Text Alignment in Python | Left, Right, Center Align & More
2024-04-11 05:59:15 Written by hayes Liu
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?
- Core Text Alignment Types in Spire.Doc
- Step-by-Step: Align Text in Word in Python
- FAQs About Python Text Alignment
- Conclusion
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.
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
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
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
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.
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:

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.