Python Docx - 部分 - 页面方向

时间:2015-08-08 13:21:27

标签: python orientation docx python-docx

以下代码尝试使用landscape方向,但文档创建为potrait.
你能说明问题所在吗?

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')

当我以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>

我不太了解XML,假设section标签应该位于顶部而不是底部的TEXT标签之上?

4 个答案:

答案 0 :(得分:12)

虽然页面被正确标记为横向,但其尺寸仍与以前相同,必须手动更改。

http://python-docx.readthedocs.io/en/latest/user/sections.html

  

页面尺寸和方向

     

剖面上的三个属性描述了页面尺寸和方向。例如,这些可以用于将部分的方向从纵向更改为横向:

...

  

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

答案 1 :(得分:2)

这里是进口

from docx import Document
from docx.shared import Inches
from docx.enum.section import WD_SECTION
from docx.enum.section import WD_ORIENT

答案 2 :(得分:0)

您是使用WordPad还是MS Word?

显示创建的文档

如果我运行以下代码:

$ 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')

我看到方向发生了变化:

$ python stackoverflow1.py
PORTRAIT (0)
LANDSCAPE (1)

但是,WordPad(我没有MS Word),文档显示在portrait:

enter image description here

答案 3 :(得分:0)

我制作了一个功能,可以轻松地从横向更改为纵向,反之亦然:

def change_orientation():
    current_section = document.sections[-1]
    new_width, new_height = current_section.page_height, current_section.page_width
    new_section = document.add_section(WD_SECTION.NEW_PAGE)
    new_section.orientation = WD_ORIENT.LANDSCAPE
    new_section.page_width = new_width
    new_section.page_height = new_height

    return new_section

然后随便使用它:

change_orientation()
document.add_picture(ax1)
change_orientation()
document.add_picture(ax2)
相关问题