我有一个函数可以通过 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 文件,您不能只读取字节并将其解析为图像。
关于python - 使用 pyPDF2 和 BytesIO 将 PDF 页面转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733539/