如何计算python中也有空白pdf页面的pdf页面的数量

Dee*_*pan 5 python-2.7

我尝试使用 pypdf 模块打印 pdf 文档的数量,其中包括一些空白的白色 pdf 页面。但它避免了空白页并打印剩余页面的计数。下面是代码。

import sys

import pyPdf

from pyPdf import PdfFileReader, PdfFileWriter

pdf_document = PdfFileReader(file(normalpdfpath,"r"))

normal = pdf_document.getNumPages()
print normal
Run Code Online (Sandbox Code Playgroud)

小智 2

你可以尝试这个,这对我有用:

import re
import os

rxcountpages = re.compile(r"/Type\s*/Page([^s]|$)", re.MULTILINE|re.DOTALL)

def count_pages(filename):
    data = file(filename,"rb").read()
    return len(rxcountpages.findall(data))

if __name__=="__main__":
    parent = "/Users/username/"
    os.chdir(parent)
    filename = 'LaTeX20120726.pdf'
    print count_pages(filename)
Run Code Online (Sandbox Code Playgroud)

对于Python 3.6+

import re

rxcountpages = re.compile(rb"/Type\s*/Page([^s]|$)", re.MULTILINE|re.DOTALL)

def count_pages(filename: str) -> int:
    with open(filename, "rb") as infile:
        data = infile.read()
    return len(rxcountpages.findall(data))

if __name__=="__main__":
    filename = '/Users/username/LaTeX20120726.pdf'
    print(count_pages(filename))
Run Code Online (Sandbox Code Playgroud)

问候

  • 已经有一段时间了,但这仍然很有用。我必须将 `data = file(filename,"rb").read()` 更改为 `data = open(filename,"rb").read()` -- 即, `open` 而不是 `file` - - 和 `re.compile(r"/Type...` 到 `re.compile(rb"/Type...` -- 即,使用二进制正则表达式。 (2认同)