word文档的页数

问题描述 投票:0回答:3

python docx 库中有一个功能可以计算文档中的页数吗?

python-docx
3个回答
4
投票

目前还不行,但是,与告诉内容中分页符在哪里的方式不同,这样的功能可以被开发。至少如果您对 Word 上次保存文档时报告的内容感到满意。

每次保存时,Word 都会将此统计信息保存在 app.xml 属性“部分”中。因此,如果您确信您正在检查的文档最后是由 Word(或我希望 LibreOffice 也可以工作)保存的,那么该方法应该非常可靠。如果文档是由 python-docx 生成的,那么该统计数据将不可靠。

如果这是您感兴趣的功能,请随时将其添加到 GitHub 问题列表中: https://github.com/python-openxml/python-docx/issues


1
投票

我想出了这个。适用于 pptx 和 docx 文件:

import zipfile
import re

archive = zipfile.ZipFile("myDocxOrPptxFile.docx", "r")
ms_data = archive.read("docProps/app.xml")
archive.close()
app_xml = ms_data.decode("utf-8")

regex = r"<(Pages|Slides)>(\d)</(Pages|Slides)>"

matches = re.findall(regex, app_xml, re.MULTILINE)
match = matches[0] if matches[0:] else [0, 0]
page_count = match[1]

print(page_count)

Office 格式只是内部包含 XML 内容的 zip 文件。您可以读取这些文件的内容并根据需要解析它们。


0
投票

修改我发现的添加页码的最佳答案,我能够添加页数。

关键是利用 MS Word 的

NumPages 默认字段

def create_element(name): return OxmlElement(name) def create_attribute(element, name, value): element.set(ns.qn(name), value) def add_page_count(run): fldChar1 = create_element('w:fldChar') create_attribute(fldChar1, 'w:fldCharType', 'begin') instrText = create_element('w:instrText') create_attribute(instrText, 'xml:space', 'preserve') instrText.text = "NumPages" fldChar2 = create_element('w:fldChar') create_attribute(fldChar2, 'w:fldCharType', 'end') run._r.append(fldChar1) run._r.append(instrText) run._r.append(fldChar2)
    
© www.soinside.com 2019 - 2024. All rights reserved.