【问题标题】:Python count pages of pdf-file that already is openPython 计算已打开的 pdf 文件的页数
【发布时间】:2021-05-09 03:21:08
【问题描述】:

我的 Python3 脚本位于网络服务器上,并接收通过互联网发送给它的 pdf 文件。因此,该 pdf 文件已作为变量的内容存在于 RAM 中,该变量是一个字节字符串:

pdf_content = b'<placeholder for the entire pdf-document>'

收到文件后不久,它将存储在服务器的硬盘上:

with open('path/to/file.pdf', 'wb') as writer:
    writer.write(pdf_content)

但我也想获取pdf文件的页数:

num_pages = get_num_pages(pdf_content)

这是我的问题:

获取已在 RAM 中作为字节串的 pdf 文档的页数的最快和最可靠的方法是什么?

换句话说:如何填充这个函数的主体?

def get_num_pages(pdf_content):
    # do something
    return num_pages

这很快但不可靠:

以下解决方案使用正则表达式查找字符串/Page 的所有匹配项。然后它返回这些发现的数量。 (变量findings是一个数组。)

def get_num_pages(pdf_content):
    findings = re.findall(b'\/Page\W', pdf_content)
    return len(findings)

此解决方案的问题在于,并非所有 pdf 文档的每一页都包含字符串 /Page 的实例。我自己的硕士论文长达 101 页,但它没有包含字符串/Page。所以这个函数说我的硕士论文是0页长,这是错误的。

我的硕士论文是由 LaTeX 编辑器创建的,可以用任何 pdf 阅读器打开。如果你想检查它,你可以从here下载它。


这可以正常工作,但速度很慢:

# use PyPDF2
from PyPDF2 import PdfFileReade

# receive the content via internet
pdf_content = b'<placeholder for the entire pdf-document>'

# write it to the hard disk (this is what I want to do anyway):
with open('path/to/file.pdf', 'wb') as writer:
    writer.write(pdf_content)

# read it again from hard disk (this is the problem):
pdf = PdfFileReader(open('path/to/file.pdf','rb'))

# retrieve the number of pages:
num_pages = pdf.getNumPages()

这个解决方案给出了正确的页数,即使是我的硕士论文,但它需要从硬盘读取内容很慢。如前所述,内容已经完全在 RAM 中,作为一个字节串。但是PdfFileReader 不接受字节串​​作为参数。这给出了一个错误:

pdf_content = b'<placeholder for the entire pdf-document>'
pdf = PdfFileReader(pdf_content)

---
Traceback (most recent call last):
  File "./test.py", line 20, in <module>
    pdf = PdfFileReader(pdf_content)
  File "/usr/local/lib/python3.6/dist-packages/PyPDF2/pdf.py", line 1084, in __init__
    self.read(stream)
  File "/usr/local/lib/python3.6/dist-packages/PyPDF2/pdf.py", line 1689, in read
    stream.seek(-1, 2)
AttributeError: 'bytes' object has no attribute 'seek'

并且documentation of PyPDF2 没有列出将纯字节字符串转换为提供搜索方法的对象的方法。

所以,我的问题又来了:获取已在 RAM 中作为字节串的 pdf 文档的页数的最快、最可靠的方法是什么?

【问题讨论】:

  • 查看其他 SO 问题和答案,了解如何将io.BytesIO 用于您的目的:stackoverflow.com/a/47801913/42346
  • 如果PdfFileReader() 得到open() 那么你可以使用PdfFileReader(io.BytesIO(pdf_content))

标签: python pdf


【解决方案1】:

如果某些函数适用于open()创建的文件处理程序

 handler = open(...)
 PdfFileReader(handler)

然后它可以与io.BytesIO()io.StringIO() 创建的类文件对象一起使用

 handler = io.BytesIO(pdf_content)
 PdfFileReader(handler)

文档:io

【讨论】:

    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2023-02-19
    • 1970-01-01
    • 2014-01-19
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多