使用 pyPDF2 和 BytesIO 将 PDF 页面转换为图像
Convert PDF page to image with pyPDF2 and BytesIO
我有一个函数可以通过 pyPdf2
从 PDF 文件中获取页面,并且应该使用 Pillow
(PIL Fork)[=16= 将第一页转换为 png(或 jpg) ]
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文件,你不能只读取字节并将其解析为图像。
并称为更健壮的实现:
我有一个函数可以通过 pyPdf2
从 PDF 文件中获取页面,并且应该使用 Pillow
(PIL Fork)[=16= 将第一页转换为 png(或 jpg) ]
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文件,你不能只读取字节并将其解析为图像。
并称为更健壮的实现: