Python pdf2image convert_from_path is failing when writing to SFTP with "expected str, bytes or os.PathLike object, not SFTPFile"

Viewed 60

I want to convert scan PDF to OCR PDF. My code is working if files is in local directories. But if I'm using SFTP the problem occurs. When I use convert_from_path using SFTP, I got an error:

expected str, bytes or os.PathLike object, not SFTPFile

How to read SFTP file path in pdf2image convert_to_path?

Here's my code:

for path in sftp.listdir_attr(file_path):
    file = file_path + path.filename
    f_name = path.filename
    with sftp.open(file) as my_file:
        print(my_file)
        pages = convert_from_path(my_file, 200)

The my_file is like this, not pathlib.path:

<paramiko.sftp_file.SFTPFile object at 0x7fa22ed55250>
<paramiko.sftp_file.SFTPFile object at 0x7fa22ed55160>
1 Answers

I do not know pdf2image. But the convert_from_path does not seem to support file-like objects.

So either you need to use different pdf2image API (if there is one).

Or you will have to resort to either

  • Downloading the SFTP file to a temporary local file and read that.

  • Or download the SFTP file to memory:

    flo = BytesIO()
    sftp.getfo(file, flo)
    flo.seek(0)
    convert_from_path(flo.read(), 200) 
    

    Note that the above is naive memory-inefficient solution.

Related