【问题标题】:Txt to Docx, page orientation to horizontalTxt 到 Docx,页面方向为水平
【发布时间】:2022-11-14 05:57:31
【问题描述】:

在将文本 (.txt) 文件转换为 Word 文档 (.docx) 时,我尝试将页面方向设置为水平。然而它并不成功。

 from docx import Document
 from docx.enum.section import WD_ORIENT
 from docx.shared import Pt

 fox = "C:\\temp\\lat.txt"
 # "there's only one lie in the text file"

 document = Document()

 sections = document.sections
 for section in sections:
     section.orientation = WD_ORIENT.LANDSCAPE

 style = document.styles['Normal']
 font = style.font
 font.size = Pt(25)

 with open(fox, encoding='utf-8') as f:
     for line in f:
         line = "\n".join(item for item in line.split('\n') if item)
         p = document.add_paragraph(line)

 document.save('C:\\temp\\lat-1.docx')

生成的 .docx 文件是垂直页面。出了什么问题,我该如何纠正?

【问题讨论】:

    标签: python docx


    【解决方案1】:

    受alexanderdamiani 在 Github 上的回答启发,(2017 年 12 月 1 日评论) https://github.com/python-openxml/python-docx/issues/298

    “解决的办法是你必须在设置横向后设置宽度和高度。所以只需抓住文档的当前宽度和高度,然后在更改方向后设置它们。”

    在上面的“section.orientation = WD_ORIENT.LANDSCAPE”之后添加以下行。

    new_width, new_height = section.page_height, section.page_width
    section.page_width = new_width
    section.page_height = new_height
    

    问题解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多