将PDF页面转换为JPG将返回空白



我有一个函数,它要求用户提供PDF文件,并接收用户希望转换为图像的页码。该函数通常工作良好,但对于一些PDF,它不起作用,返回的图像是空白的,并且有4兆字节。显然,这与文件的大小有关。有办法解决这个问题吗?

from PyPDF2 import PdfFileReader, PdfFileWriter
from tkinter.filedialog import askopenfilename
from pdf2image import convert_from_path
import os
import PIL
PIL.Image.MAX_IMAGE_PIXELS = None
def convert_pdf(page_number):
filename = askopenfilename()
pdf_file_path = filename
file_base_name = pdf_file_path.replace('.pdf', '')
pdf = PdfFileReader(pdf_file_path)
pages = [page_number]
pdfWriter = PdfFileWriter()
for page_num in pages:
pdfWriter.addPage(pdf.getPage(page_num))
with open('{0}_subset.pdf'.format(file_base_name[:-5]), 'wb') as f:
pdfWriter.write(f)
f.close()
n = file_base_name[:-5]
nome = f'{n}_subset.pdf'
pages = convert_from_path(nome, poppler_path=r'C:Program Filespoppler-0.68.0bin')
i = 1
name = os.path.basename(nome).split('/')[-1][:-4]
for page in pages:
image_name = "Page_" + str(i) + f"{name}.jpg"
page.save(image_name, "JPEG")
i = i + 1

此问题的解决方案是更改convert_from_path函数的DPI参数。保持DPI的原样很重要,因为我发现某些图像变得非常小,因此无法读取。

try:
pages = convert_from_path(nome, poppler_path=r'C:Program Filespoppler-0.68.0bin')
i = 1
except:
PIL.Image.MAX_IMAGE_PIXELS = None
pages = convert_from_path(nome, 25,poppler_path=r'C:Program Filespoppler-0.68.0bin')
i = 1

相关内容

  • 没有找到相关文章

最新更新