阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not guarantee effectiveness for all real files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.
Which problem does this paper address first
After constructing all sections, re-fetch the target section by its index to avoid mistakenly treating the last section object saved before adding new subsections as the original section. Set the orientation and page dimensions separately, and after saving, re-read the document to verify that no other sections have been altered.
self-contained synthetic example
dependencies are listed in the import section. The code constructs inputs in memory; runtime logs are provided separately and do not constitute a guarantee for all real-world files.
from docx import Document
from docx.enum.section import WD_ORIENT, WD_SECTION
from io import BytesIO
doc = Document()
doc.add_paragraph("Portrait intro")
doc.add_section(WD_SECTION.NEW_PAGE)
doc.add_paragraph("Landscape middle")
doc.add_section(WD_SECTION.NEW_PAGE)
doc.add_paragraph("Portrait end")
middle = doc.sections[1]
width, height = middle.page_width, middle.page_height
middle.orientation = WD_ORIENT.LANDSCAPE
middle.page_width, middle.page_height = max(width, height), min(width, height)
out = BytesIO()
doc.save(out)
out.seek(0)
restored = Document(out)
assert len(restored.sections) == 3
assert restored.sections[1].orientation == WD_ORIENT.LANDSCAPE
assert restored.sections[1].page_width > restored.sections[1].page_height
assert restored.sections[0].orientation == WD_ORIENT.PORTRAIT
assert restored.sections[2].orientation == WD_ORIENT.PORTRAIT
In Word document automation, setting a specific wide table page to landscape while keeping the remaining pages in portrait orientation is one of the most common pitfalls. Many developers attempt to directly modify paragraph or table properties, only to end up either with the entire document turned into landscape or with the table rotated and its content overflowing and getting cropped. The root cause lies in confusing “page breaks” (Page Break) with “section breaks” (Section Break): page breaks merely control line breaks and carry no layout attributes, whereas settings such as page orientation, paper size, and margins are all strictly tied to the “section” container. To achieve localized landscape orientation, you must insert section breaks before and after the target content and precisely adjust the properties of that particular section.
section break is the true carrier of page layout attributes
in the OpenXML standard,
<w:sectPr>
The element defines the page layout. A document can contain multiple sections, each of which independently has its own width, height, orientation, and margin settings. When you call
document.add_section()
At that time, python-docx will create a new one at the end of the current document.
<w:sectPr>
, any content added afterward will automatically be assigned to this new section. If you attempt to change the orientation by modifying paragraph styles or table properties, it is bound to fail, as these objects simply do not have fields for storing layout information.
Once this is understood, the operational logic becomes clear: first, locate the content range that needs to be rotated, ensuring it is enclosed within a separate section; then, swap the section’s width and height values and set the orientation to LANDSCAPE. Note that merely setting the orientation without swapping the dimensions will cause Word to display an incorrect paper size upon opening, resulting in content being cropped when printing or exporting to PDF. This is the most common mistake made by beginners and also the central point emphasized in this article.
synthesis example: correct rotation versus common boundary errors
The following is a set of
synthesis example
, used to demonstrate expected behavior and error handling, is not real business data. If you need to process external files, please use
Document('path/to/file.docx')
is loaded, and it is ensured that the file is unencrypted and structurally intact.
correct input scenario
: The document contains three sections: the first is in portrait orientation, the second requires a wide table, and the third returns to portrait orientation. The expected output is the second section.
orientation
is LANDSCAPE, and
page_width
is greater than
page_height
, while the other two sections remain unchanged as PORTRAIT.
error/boundary input
: Given a single-section document that has never been explicitly sectioned, directly process
sections[0]
Perform landscape orientation. At this point, modifying without any checks would cause the entire document to switch to landscape. The correct approach is to first check the number of sections; if there is only one section and the requirement is merely a partial rotation, you should first call
add_section()
Split the content, then perform operations on the newly generated section. Another boundary condition is when the width and height have not been swapped: if LANDSCAPE is set but the original portrait dimensions are retained, the code should enforce validation.
page_width >= page_height
serves as the precondition.
python-docx local horizontal layout code implementation
The following example demonstrates how to construct a three-section document in memory and safely set the middle section to landscape orientation. The dependency library is
python-docx
Please run it in the locked project environment; the version must be supported.
WD_ORIENT
enumeration (from 0.8.11 and above). The example does not include file read/write operations; all objects are constructed in memory, and readers may replace them with actual file paths for testing.
Acceptance Checklist and Manual Review Boundary
code can handle well-structured documents, but real-world files often exhibit unexpected conditions. The table below lists key acceptance criteria and the points at which automation should be abandoned:
Observation of the phenomenon
processing decision
Whether the code demonstration is applicable
The target page has no section breaks before or after
first uses
add_section()
splitting, then setting the direction
is
remains truncated even after setting the horizontal alignment
checks whether the left and right margins of the section are too large, or whether the table width exceeds the page size
No, the margins or the table need to be adjusted.
document contains a continuous section break and has an abnormal orientation
Continuous section breaks do not start on a new page, which may lead to visual clutter; it is recommended to switch to a next-page section break.
Partially applicable; manual determination of section type is required.
The number of elements is 0, or accessing the index results in an IndexError.
uses
len(sections)
pre-check, or try-except fallback
is
header and footer are horizontally misaligned on
section attribute changes do not affect the header link status; the header/footer distance must be checked separately
No, it is an independent issue
explicitly specifies the inapplicable scenarios: encrypted documents, corrupted XML structures, and template files that use macros to dynamically generate sections. In these cases, manual repair or format conversion should be performed first. The code demonstration only validates the API call logic; end-to-end results must be visually confirmed after exporting to Word or PDF.
Reference and Next Step
python-docx Sections Official Documentation
uses this checklist for document translation
Word translations often conflate content issues with formatting problems. Leave checks for styles, headers, tables, and other elements to the delivery checklist, so that reviewers know where to look.
OmniDoc (Product Entry)
provides an entry point for translating multi-format documents, and the official website highlights its OCR, terminology database, and bilingual alignment features. For teams that wish to start processing directly from files, this is a path worth evaluating with real-world samples. Please use de-identified files that you are authorized to upload, and verify the results against the checklist provided in this document; we do not claim that OmniDoc utilizes the open-source libraries or internal algorithms referenced herein, nor do we substitute examples for product performance testing.
- 1 -
Updated 2026-10-09