python 批量修改word文档页眉页脚

查看 27|回复 0
作者:Eks6666   
[Python] 纯文本查看 复制代码from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
from docx.shared import Inches
import os
doc = Document('test.docx')
def update_header_footer(doc, header_logo, footer_text, save_file_name):
    section = doc.sections[0]
    header = section.header
    header_paragraph = header.paragraphs[0]
    # 这里既可以添加图片也可以添加文字
    run = header_paragraph.add_run()
    logo_path = header_logo
    run.add_picture(logo_path, width=Inches(1))
    # 这里是添加文字的代码
    # header_paragraph.text = "这里是页眉"
    # header_paragraph.style.font.size = Pt(12)
    header_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    footer = section.footer
    footer_paragraph = footer.paragraphs[0]
    footer_paragraph.text = footer_text
    footer_paragraph.style.font.size = Pt(12)
    footer_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    # 访问并修改页眉
    # header = doc.sections[0].header
    # header.paragraphs[0].text = '新的页眉内容'
    # footer = doc.sections[0].footer
    # footer.paragraphs[0].text = '新的页脚内容'
    # header_paragraph = doc.sections[0].header.paragraphs[0]
    # run = header_paragraph.add_run()
    # logo_path = './imgs/image1_37419.png'
    # run.add_picture(logo_path, width=Inches(1))
    doc.save(save_file_name)
def update_all_doc(directory, header_logo, footer_text):
    os.makedirs(save_dirs, exist_ok=True)
    for filename in os.listdir('./'):
        try:
            if filename.endswith('.docx'):
                # doc_path = filename
                doc_path = filename
                print(doc_path)
                doc = Document(doc_path)
                save_file_name = os.path.join(save_dirs, filename)
                update_header_footer(
                    doc, header_logo, footer_text, save_file_name)
        except:
            continue
if __name__ == "__main__":
    directory = "outputdoc"
    header_logo = "./imgs/image1_37419.png"
    footer_text = '© 2024 Honoreal. All rights reserved.'
    save_dirs = "add header and footer"
    update_all_doc(directory, header_logo, footer_text)

页眉, 批量

您需要登录后才可以回帖 登录 | 立即注册

返回顶部