Python Docx - Sections - Page Orientation
The following code tries to use orientation landscape
, but the document is generated like potrait.
Can you suggest where the problem is?
from docx import Document
from docx.enum.section import WD_ORIENT
document = Document()
section = document.sections[-1]
section.orientation = WD_ORIENT.LANDSCAPE
document.add_heading('text')
document.save('demo.docx')
When I read the code as XML
<w:document>
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="Heading1"/>
</w:pPr>
<w:r>
<w:t>TEXT</w:t>
</w:r>
</w:p>
<w:sectPr w:rsidR="00FC693F" w:rsidRPr="0006063C" w:rsidSect="00034616">
<w:pgSz w:w="12240" w:h="15840" w:orient="landscape"/>
<w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="720" w:footer="720" w:gutter="0"/>
<w:cols w:space="720"/>
<w:docGrid w:linePitch="360"/>
</w:sectPr>
</w:body>
</w:document>
I don't know XML well, assuming the section tags should go above the TEXT tags at the top and not the bottom ????
source to share
As long as a page is correctly marked as landscape, its dimensions remain the same and must be manually resized.
http://python-docx.readthedocs.io/en/latest/user/sections.html
Page sizes and orientation
Three properties in the section describe the page size and orientation. Together they can be used, for example, to change the orientation of a section from portrait to landscape:
...
new_width, new_height = section.page_height, section.page_width section.orientation = WD_ORIENT.LANDSCAPE section.page_width = new_width section.page_height = new_height
source to share
You display the generated document with WordPad
or withMS Word?
If I run the following code:
$ cat stackoverflow1.py
import sys
from docx import Document
from docx.enum.section import WD_ORIENT
document = Document()
section = document.sections[0]
print section.orientation
section.orientation = WD_ORIENT.LANDSCAPE
print section.orientation
document.add_heading('text')
document.save('demo.docx')
I can see that the orientation changes:
$ python stackoverflow1.py
PORTRAIT (0)
LANDSCAPE (1)
But, on WordPad
(I don't have MS Word), the document is displayed inportrait:
source to share