Adjusting Document Page Layout
When creating a document, sometimes you may need to work in landscape orientation
or require more margins
.
A document's page layout
helps enhance readability and clarity of the content.
With python-docx, you can easily adjust the page size, margins, orientation, and more using Python code.
In this lesson, we will learn how to adjust the page layout.
What is a Page Section?
A section is a unit used to set up the layout of a document page.
In python-docx, the sections
property is used to adjust attributes such as page size, margins, and orientation.
A document can consist of multiple sections, each with its own page setup.
Setting Page Orientation
To set the page orientation to portrait or landscape, use the orientation
property.
In python-docx, you can set the orientation using the WD_ORIENTATION
class.
from docx.enum.section import WD_ORIENTATION # Set orientation to landscape section.orientation = WD_ORIENTATION.LANDSCAPE
This code sets the page to landscape orientation. The default document orientation is portrait.
Setting Page Size
To adjust the page size, use the page_width
and page_height
properties.
For example, to set the page size to A4 (21.0cm x 29.7cm), you can write the code as follows:
from docx.shared import Cm section = doc.sections[0] section.page_width = Cm(21.0) section.page_height = Cm(29.7)
Setting Page Margins
You can set the page margins using the top_margin
, bottom_margin
, left_margin
, and right_margin
properties.
section.top_margin = Cm(2.5) section.bottom_margin = Cm(2.5) section.left_margin = Cm(3.0) section.right_margin = Cm(3.0)
This code sets the top and bottom margins to 2.5cm, and the left and right margins to 3.0cm.
What is the most appropriate content to fill in the blank?
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result
The document is empty.
Try running the code.