pythonpdfpython-imaging-libraryimg2pdf

Invalid rotation when converting jpg to pdf with python


I'm trying to convert a jpg to pdf with img2pdf.

It works with most jpg's but not all.

Here is my script:

import img2pdf
import PIL.Image
import os
image = PIL.Image.open("Lidl.jpg")
pdf_bytes = img2pdf.convert(image.filename)
file = open(pdf_path, "wb")
file.write("file.pdf")
image.close()
file.close()

Here is the error I get:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    pdf_bytes = img2pdf.convert(image.filename)
  File "/home/ksb/Dropbox/Python/imap/venv/lib/python3.6/site-packages/img2pdf.py", line 1829, in convert
    ) in read_images(rawdata, kwargs["colorspace"], kwargs["first_frame_only"]):
  File "/home/ksb/Dropbox/Python/imap/venv/lib/python3.6/site-packages/img2pdf.py", line 1191, in read_images
    imgdata, imgformat, default_dpi, colorspace, rawdata
  File "/home/ksb/Dropbox/Python/imap/venv/lib/python3.6/site-packages/img2pdf.py", line 1030, in get_imgmetadata
    'Image "%s": invalid rotation (%d)' % (im.name, value)
NameError: name 'im' is not defined

If I look into the image meta data it says:

Unknown rotation value 0
ColorSpace=sRGB

Is is possible to set the rotation value?

Any hints are very much appreciated.

BR Kresten


Solution

  • I guess the problem is with below code line.

    file.write("file.pdf")
    

    Here try passing the bytes you got from convert function.

    file.write(pdf_bytes)
    

    For the error you are getting you may try as said below. Try using library imdirect

    from PIL import Image
    import imdirect
    img = Image.open('Lidl.jpg')
    img_rotated = imdirect.autorotate(img)
    

    The above code snippet is copied from project description page of the library. Also read the quick description, to know why such problems occur.

    https://pypi.org/project/imdirect/

    If still not working, as a part of last try, rotate the image after opening and before converting into bytes, with the desired angle that satisfies your requirement.

    image = PIL.Image.open("Lidl.jpg")
    image.rotate(90) #90 is rough number, you calculate, what you need.
    pdf_bytes = img2pdf.convert(image.filename)