Python設置Word頁面紙張方向為橫向
實現(xiàn)思路
通過python-docx的章節(jié)屬性,就可以更改紙張方向、紙張尺寸。
import docx
from docx.enum.section import WD_ORIENT
from docx.shared import Cm
document = docx.Document()
section = document.sections[0]
# 設置紙張大小為A4大小
section.page_width = Cm(21)
section.page_height = Cm(29.7)
# 設置紙張方向橫向,橫向是LANDSCAPE,豎向是PORTRAIT
section.orientation = WD_ORIENT.LANDSCAPE
# 設置章節(jié)寬高,也就是寬高互換
section.page_width, section.page_height = section.page_height, section.page_width
document.save('landscape.docx')
更改紙張方向,分兩步,第一步是設置section的orientation屬性為LANDSCAPE,第二步是設置section的寬高互換。


相關鏈接
知識補充
除了上文的方法,小編還為大家整理了其他Python設置紙張方向的方法,希望對大家有所幫助
Python-docx設置紙張方向為橫向
第一種,設置當前頁面方向為橫線
from docx import Document
from docx.enum.section import WD_ORIENT
#這里能夠獲取到當前的章節(jié),也就是第一個章節(jié)
section = document.sections[0]
#需要同時設置width,height才能成功
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
#保存docx文件
document.save('test3.docx')
第二種,設置所有章節(jié)的頁面方向均為橫向
from docx import Document
from docx.enum.section import WD_ORIENT
#獲取本文檔中的所有章節(jié)
sections = document.sections
#將該章節(jié)中的紙張方向設置為橫向
for section in sections:
#需要同時設置width,height才能成功
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
document.save('test2.docx')
第三種,分別設置為每一章節(jié)的紙張方向,處理結(jié)果為:第一章節(jié)為縱向,第二章節(jié)為橫向,第三章節(jié)為縱向
from docx import Document
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START # 導入節(jié)方向和分節(jié)符類型
document = Document() # 新建docx文檔
document.add_paragraph() # 添加一個空白段落
section = document.add_section(start_type=WD_SECTION_START.CONTINUOUS) # 添加橫向頁的連續(xù)節(jié)
section.orientation = WD_ORIENTATION.LANDSCAPE # 設置橫向
page_h, page_w = section.page_width, section.page_height
section.page_width = page_w # 設置橫向紙的寬度
section.page_height = page_h # 設置橫向紙的高度
document.add_paragraph() # 添加第二個空白段落
section = document.add_section(start_type=WD_SECTION_START.CONTINUOUS) # 添加連續(xù)的節(jié)
section.orientation = WD_ORIENTATION.PORTRAIT # 設置縱向
page_h, page_w = section.page_width, section.page_height # 讀取插入節(jié)的高和寬
section.page_width = page_w # 設置縱向紙的寬度
section.page_height = page_h # 設置縱向紙的高度
document.save('test.docx')到此這篇關于Python設置Word頁面紙張方向為橫向的文章就介紹到這了,更多相關Python設置Word頁面方向內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python?中?關于reverse()?和?reversed()的用法詳解
這篇文章主要介紹了python?中?關于reverse()?和?reversed()的用法介紹,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
Python如何爬取微信公眾號文章和評論(基于 Fiddler 抓包分析)
這篇文章主要介紹了Python如何爬取微信公眾號文章和評論(基于 Fiddler 抓包分析),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-06-06

