Python PIL由于某些原因无法打开PDF

时间:2018-06-26 17:12:49

标签: python python-2.7 pdf python-imaging-library

所以我的程序能够打开PNG,而不能打开PDF,所以我只是为了测试而已,即使是简单的PDF也无法打开。而且我不知道为什么。

from PIL import Image

with Image.open(r"Adams, K\a.pdf") as file:
    print file

Traceback (most recent call last):
  File "C:\Users\Hayden\Desktop\Scans\test4.py", line 3, in <module>
    with Image.open(r"Adams, K\a.pdf") as file:
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2590, in open
    % (filename if filename else fp))
IOError: cannot identify image file 'Adams, K\\a.pdf'

按照建议尝试PyPDF2后(顺便感谢链接),我的代码出现此错误。     导入PyPDF2

pdf_file= open(r"Adams, K (6).pdf", "rb")
read_pdf= PyPDF2.PdfFileReader(pdf_file)

number_of_pages = read_pdf.getNumPages()
print number_of_pages


Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]

2 个答案:

答案 0 :(得分:2)

@Kevin指出(请参见下面的评论),PIL支持writing pdfs but not reading them

要阅读pdf,您将需要其他一些库。您可以查看here,这是使用PyPDF2处理PDF的教程。

https://pythonhosted.org/PyPDF2/?utm_source=recordnotfound.com

答案 1 :(得分:0)

按照这篇文章:https://www.geeksforgeeks.org/convert-pdf-to-image-using-python/ 您可以使用 pdf2image 包将 pdf 转换为 PIL 对象。

这应该可以解决您的问题:

from pdf2image import convert_from_path

fname = r"Adams, K\a.pdf"
pil_image_lst = convert_from_path(fname) # This returns a list even for a 1 page pdf
pil_image = pil_image_lst[0]

我只是用一页 pdf 试了一下。