栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python-docx页眉横线

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python-docx页眉横线

页眉横线实际上是一种边框形式

方法一下划线仅支持18种格式,详见Word 中的 WdUnderline (枚举) | Microsoft Docs

方法二支持页眉横线所有样式,但需要修改源代码,详见OOXML w:ST_Border - 完整的文档和示例 (datypic.com)

方法一:使用docx下划线及tab-stop制作页眉横线

import docx
import os
import subprocess
from docx import document

# from win32com.client import Dispatch 
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.text import WD_UNDERLINE
from docx.enum.text import WD_TAB_ALIGNMENT
from docx.enum.table import WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_LINE_SPACING

class xxxx():

    def loadfile(self):
        pass
    
    def header(self,file):

        document = document(file) # 新建文档
        #设置页眉
        header = document.sections[0].header # 获取第一个节的页眉
        # 通过分区添加页眉横线
        header.add_paragraph(
            "tt"
        ).paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        header_para = header.paragraphs[-1]
        # style1:与页边距齐平
        header_para.paragraph_format.left_indent = 0
        header_para.paragraph_format.right_indent = 0
        # #style2:横穿整个页面故段落边距紧贴页边
        # header_para.paragraph_format.left_indent = - document.sections[0].left_margin
        # header_para.paragraph_format.right_indent = - document.sections[0].right_margin
        # 设置制表位分区
        tab_stops = header_para.paragraph_format.tab_stops
        tab_stops.add_tab_stop(docx.shared.Inches(3.5), WD_TAB_ALIGNMENT.CENTER)
        tab_stops.add_tab_stop(docx.shared.Inches(6.5), WD_TAB_ALIGNMENT.RIGHT)
        # 设置横线样式
        header_para.runs[-1].underline = WD_UNDERLINE.THICK #厚 DOUBLE双下划线
        #行高为确定值
        header_para.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
        header_para.height = docx.shared.Pt(1)
        #line_space为确定值
        header_para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY 
        header_para.line_spacing = docx.shared.Pt(1)

上述代码引用包说明:

import subprocess

from win32com.client import Dispatch

目的均为使doc转为docx文件,

前一种是mac下载LibreOffice后使用;后一种仅支持win(mac不能用,原理貌似是pypiwin32是将文件以win32位二进制流编写转码,仅支持win。详见stackover)


方法二:修改源代码,添加border

见该pull request修改代码:(红的删除,绿的添加)但由于这种方式并未merge到module,需要手动更新。下一步计划:学习XML,读懂python-docx文档达到能自己改源码的水平



Enable python-docx to add border by xxxspy · Pull Request #326 · python-openxml/python-docx · GitHub

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/752955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号