python - 使用 pyPDF2 和 BytesIO 将 PDF 页面转换为图像

标签 python pdf pypdf bytesio

我有一个函数可以通过 pyPdf2 从 PDF 文件中获取页面,并且应该使用 Pillow 将第一页转换为 png(或 jpg)(PIL Fork)

from PyPDF2 import PdfFileWriter, PdfFileReader
import os
from PIL import Image
import io

# Open PDF Source #
app_path = os.path.dirname(__file__)
src_pdf= PdfFileReader(open(os.path.join(app_path, "../../../uploads/%s" % filename), "rb"))

# Get the first page of the PDF #
dst_pdf = PdfFileWriter()
dst_pdf.addPage(src_pdf.getPage(0))

# Create BytesIO #
pdf_bytes = io.BytesIO()
dst_pdf.write(pdf_bytes)
pdf_bytes.seek(0)

file_name = "../../../uploads/%s_p%s.png" % (name, pagenum)
img = Image.open(pdf_bytes)
img.save(file_name, 'PNG')
pdf_bytes.flush()

这会导致错误:

OSError: cannot identify image file <_io.BytesIO object at 0x0000023440F3A8E0>

我发现一些线程有类似的问题,( PIL open() method not working with BytesIO ) 但我看不出我哪里错了,因为我已经添加了 pdf_bytes.seek(0)

感谢任何提示

最佳答案

每个文档:

write(stream) Writes the collection of pages added to this object out as a PDF file.

Parameters: stream – An object to write the file to. The object must support the write method and the tell method, similar to a file object.

因此对象 pdf_bytes 包含一个 PDF 文件,而不是图像文件。

之所以有像上面这样的代码是因为:有时,pdf 文件只包含一个 jpeg 文件作为其内容。如果您的 pdf 只是一个普通的 pdf 文件,您不能只读取字节并将其解析为图像。

并引用更强大的实现:https://stackoverflow.com/a/34116472/334999

关于python - 使用 pyPDF2 和 BytesIO 将 PDF 页面转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733539/

相关文章:

python - 如何对数字列表进行排名并打印出排名?

pdf - 为pdf页面添加边距

python - 使用 pyPDF 从文档中检索自定义页面标签

Python - 创建多层PDF

python - 对于大型数组的手动元素操作,numpy 的更快替代方案?

python - 如何通过迭代另一个工作表同时排除数组中的某些行来创建工作表的副本?

python - 完全可解析的词典/词库

ios - 如何在推送 View 之前加载 PDF

vba - 检查 PDF 是否发送到打印机