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

标签 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]

最佳答案

继本文之后: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 尝试过这一点。

关于Python PIL 由于某种原因无法打开 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51048266/

相关文章:

flutter - 尝试在 flutter 中创建不同语言的 pdf

python - 如何在Python中生成随机范围?

python - 将 OpenCV 与 Tkinter 结合使用

python - 函数的返回值是none

javascript - 当我呈现整个文档时,React 和 PDF.js 更改页面不起作用

java - 使用 servlet 传递 PDF

python - 不可变对象(immutable对象)的名称如何重新绑定(bind)到扩充赋值的结果?

python - Python 内置哈希函数的十六进制摘要

python - Python2.7获取pip包

python - 十进制 ('5E+1' ) 可以在 Python 中简单地转换为十进制 ('50' ) 吗?