Python: Set Page Margins for Word Documents

Setting proper margins is an essential step in creating professional Word documents. Margins may seem like a small detail, but they play a vital role in improving the readability and visual appeal of a document. By defining the space around content, margins help maintain a consistent and balanced layout, prevent text from being truncated, and make documents look more organized and aesthetically pleasing. This article will show how to use Spire.Doc for Python to set page margins for Word documents through 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 this tutorial: How to Install Spire.Doc for Python on Windows

Set the Page Margins of a Word Document

Spire.Doc for Python provides properties under the Margins class that can be used to set margins for each side of a document separately or to set the same margins for all sides. One important thing to note is that the margins are set based on sections. For consistent margins throughout the document, it is necessary to iterate through each section of the document to set the margins. Below are the detailed steps for setting page margins:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Loop through the sections of the document.
  • Get a section using Document.Sections.get_Item() method.
  • Get the margins of the section using Section.PageSetup.Margins property.
  • Set the top, bottom, left, and right margin using property under Margins class.
  • 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")

# Loop thorugh the sections of document
for i in range(doc.Sections.Count):
    # Get a section
    section = doc.Sections.get_Item(i)
    # Get the margins of the section
    margins = section.PageSetup.Margins
    # Set the top, bottom, left, and right margins
    margins.Top = 17.9
    margins.Bottom = 17.9
    margins.Left = 20.9
    margins.Right = 20.9
    # margins.All = 17.9

# Save the document
doc.SaveToFile("output/SetPageMargins.docx", FileFormat.Auto)

Python: Set Page Margins for 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.