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.
Lessons in this chapter · How to automate repetitive PowerPoint and Word tasks using Python code
- 1. How to Automate Repetitive PowerPoint Tasks
- 2. Adding Text Box and Text to Slides
- 3. Changing Font, Size, and Color of Text Formatting
- 4. Inserting and Adjusting Images on a Slide
- 5. Creating and Managing Tables in Slides
- 6. Inserting Excel Data into a Slide as a Table
- 7. Creating Charts and Visualizing Data with Python
- 8. Fill-in-the-blank quiz
- 9. Create Word Documents with Python Code
- 10. Adding and Formatting Paragraphs
- 11. Creating Lists
- 12. How to Create Tables with Python Code
- 13. Inserting and Styling Images in Your Document
- 14. Adjusting Document Page Layout
- 15. Read Excel with openpyxl & Write to Word
- 16. Multiple-choice quiz
- 17. Challenge Yourself! Creating a Simple Table with python-docx
What is the most appropriate content to fill in the blank?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help