Charlie Zhang
Charlie Zhang

Reputation: 65

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

I wanted to make a Python program that converts PDFs to PNGs, but when I ran the code it showed an error for some reason.

Here's my code:

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")

And it shows this error:

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?

Does anyone know a solution to this problem, that would be really useful

Upvotes: 1

Views: 812

Answers (1)

Thyrus
Thyrus

Reputation: 466

pdf2image library is using pdttoppm with subporcess.Popen. So try to do it directly. and you can use filedialog.askopenfilename() to specify file

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))

You can also use wand to do it, check for wand library.

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)

Upvotes: 1

Related Questions