如何使用Python将PDF转换为图像?

5
所以我正在使用Wand尝试将PDF转换为图像。
from wand.image import Image

with Image(filename="test.pdf") as img:
     img.save(filename="/temp.jpg")

with Image(filename="test.jpg") as img:
     img.resize(200, 150)
     img.save(filename="t.jpg")

但由于某种原因,我得到:

Traceback (most recent call last):
  File "C:\Users\Rafael\Desktop\k\pdf to image.py", line 3, in <module>
    with Image(filename="test.pdf") as img:
  File "C:\Python27\lib\site-packages\wand\image.py", line 2534, in __init__
    self.read(filename=filename, resolution=resolution)
  File "C:\Python27\lib\site-packages\wand\image.py", line 2601, in read
    self.raise_exception()
  File "C:\Python27\lib\site-packages\wand\resource.py", line 222, in raise_exception
    raise e
DelegateError: PDFDelegateFailed `The system cannot find the file specified.

' @ error/pdf.c/ReadPDFImage/798

有没有其他方法可以将PDF转换为图片?我能做些什么吗?

你确定路径是“test.pdf”吗?听起来好像文件不存在,或者程序无法从当前目录中看到它。 - Jerfov2
是的,我确定了,我甚至尝试了完整路径。 - Rafas
看起来 ImageMagick 没有配置“--with-lqr”选项。确保你的 Python 和 ImageMagick 版本确实是相同的(32/64 位)。如果版本存在冲突,卸载 ImageMagick 并安装兼容的版本。 - Nickil Maveli
我已经检查过,两者都是64位的。 - Rafas
可能是PythonMagick找不到我的PDF文件的重复问题。 - Basj
4个回答

2
安装 Ghostscript 并添加
C:\Program Files (x86)\gs\gs9.06\bin

systempath添加到您的路径中应该有助于解决此问题,因为它帮助我克服了这个错误...


1

0
我最喜欢的方法是使用PyMuPDF来完成这个任务。

安装软件包

pip install PyMuPDF

使用方法

import fitz  # installed via pymupdf!

# To get higher resolution
zoom_x = 2.0
zoom_y = 2.0
matrix = fitz.Matrix(zoom_x, zoom_y)

doc = fitz.open("becomes-black.pdf")
for page in doc:
    pix = page.get_pixmap(matrix=matrix)
    pix.save(f"page-{page.number}.png")

0

还有另一种方法。看起来你正在使用Windows,所以你需要下载“https://github.com/oschwartz10612/poppler-windows/releases/”。 因为你正在使用Windows,所以你需要指定poppler/bin文件夹的路径: 代码:

from pdf2image import convert_from_path

poppler_path = "C:\path\to\poppler\bin"

images = convert_from_path('example.pdf')

for i in range(len(images)):

  
    images[i].save('page'+ str(i) +'.jpg', 'JPEG')

参考: https://www.geeksforgeeks.org/convert-pdf-to-image-using-python/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接