我试图用 Python 制作一个 pdf 到图像的转换器,但它显示错误

I tried to make a pdf to image converter with Python but it shows an error

我想制作一个 Python 将 PDF 转换为 PNG 的程序,但是当我 运行 代码时,由于某种原因它显示错误。

这是我的代码:

from pdf2image import convert_from_path
from tkinter import filedialog

filename = filedialog.askopenfilename()
images = convert_from_path(filename)
 
for i in range (len(images)):
    images[i].save("page" + str(i) + ".png")

它显示了这个错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pdf2image/pdf2image.py", line 458, in pdfinfo_from_path
    proc = Popen(command, env=env, stdout=PIPE, stderr=PIPE)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 1842, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'pdfinfo'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/charliezhang/Desktop/pdf_to_png.py", line 5, in <module>
    images = convert_from_path(filename)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pdf2image/pdf2image.py", line 98, in convert_from_path
    page_count = pdfinfo_from_path(pdf_path, userpw, poppler_path=poppler_path)["Pages"]
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pdf2image/pdf2image.py", line 484, in pdfinfo_from_path
    raise PDFInfoNotInstalledError(
pdf2image.exceptions.PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH?

有谁知道这个问题的解决方案,那真的很有用

pdf2image 库将 pdttopm 与 subporcess.Popen 结合使用。所以尝试直接做。您可以使用 filedialog.askopenfilename() 来指定文件

import subprocess

path_to_pdftoppm = r"C:\Users\Yourname\software\...."
file_to_open="your_file.pdf"

subprocess.Popen('"%s" -png "%s" out' % (path_to_pdftoppm,file_to_open))

你也可以用魔杖来做,检查魔杖库。

from wand.image import Image

file = "yourfile.pdf"
with(Image(filename=file, resolution=120)) as source: 
    for i, image in enumerate(source.sequence):
        newfilename = file[:-4] + str(i + 1) + '.png'
        Image(image).save(filename=newfilename)