6

I'm attempting to convert a JPEG file with, 200 dpi, to a PDF file, however, when I save the file as a PDF I think it's changing the dpi to 72, and thus making the image larger. I had a similar problem when initially trying to scale my JPEG image to a smaller size, and was able to solve that by specifying the dpi when I save the image.

im = Image.open("Image.jpg")

dpi=im.info['dpi']

if im.size == (2592, 1728):
    out = im.resize((1188,792), Image.ANTIALIAS)
elif im.size == (1728,2592):
    out = im.resize((792,1188), Image.ANTIALIAS)

out.save(project, dpi=dpi)

Now when I try to save this JPEG as a PDF, specifying the dpi doesn't seem to make any difference, and I get an image that is larger than my original that looks like it has a lower dpi. Is there a way to mantain a consistent resolution when converting from JPEG to PDF using PIL? Or is there a better way for me to go about doing this?

This is what I have for converting a directory of files from JPEG to PDF:

for infile in listing:

    outfile = destpath + os.path.splitext(infile)[0] + ".pdf"
    current = path + infile

    if infile != outfile:
        im = Image.open(current)
        dpi=im.info['dpi']

        im.save(outfile, "PDF", Quality = 100)
3
  • What is the dpi value that PIL reads from the jpeg? Is it, in fact, 200?
    – jedwards
    Commented Sep 27, 2012 at 17:40
  • @jedwards yup, i threw a print statement in there and it said the dpi of the jpeg was (200,200). Commented Sep 27, 2012 at 17:45
  • 1
    I'm quite surprised that PIL supports PDF at all. I'm sure it's a primitive conversion. Commented Sep 27, 2012 at 18:58

7 Answers 7

11

In the CHANGES file of PIL 1.1.7 sources one can read:

  • Added resolution save option for PDF files.

    Andreas Kostyrka writes: I've included a patched PdfImagePlugin.py
    based on 1.1.6 as included in Ubuntu, that supports a "resolution"
    save option. Not great, but it makes the PDF saving more useful by
    allowing PDFs that are not exactly 72dpi.

So you should be able to do:

im.save(outfile, "PDF", resolution=100.0)

(seems to work fine on my Ubuntu box).

4
  • Are you sure it works? On my system, using identify -verbose (ImageMagick) I get: Resolution: 72x72
    – jedwards
    Commented Sep 27, 2012 at 18:46
  • @jedwards, it works for me on Windows too. Remember that Python is case sensitive, I used a capital R the first time and it didn't work. I also used an integer for the parameter, I don't know if that makes a difference or not. Commented Sep 27, 2012 at 19:04
  • 1
    @MarkRandom, it turns out ImageMagick was lying (sort of). PDF's don't have a DPI by themselves, so I guess it makes sense that ImageMagick reports 72 by default. Instead, the individual elements contained within a PDF do. Using Acrobat's preflight check you can look at the individual elements' DPI -- which confirmed that this does work (Image.VERSION = 1.1.7). Sorry for the confusion.
    – jedwards
    Commented Sep 27, 2012 at 19:52
  • This worked! though I has to set resolution = 200.0 for the pdf to be the same dimensions as the jpeg. Set at 100.0 and the dimensions were doubled. Commented Sep 27, 2012 at 20:51
6

You can use reportlab library.

import sys

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, flowables

__jpgname = str()
def drawPageFrame(canvas, doc):
    width, height = letter
    canvas.saveState()
    canvas.drawImage(
    __jpgname, 0, 0, height, width,
    preserveAspectRatio=True, anchor='c')
    canvas.restoreState()

def jpg2pdf(pdfname):
    width, height = letter

    # To make it landscape, pagesize is reversed
    # You can modify the code to add PDF metadata if you want
    doc = SimpleDocTemplate(pdfname, pagesize=(height, width))
    elem = []

    elem.append(flowables.Macro('canvas.saveState()'))
    elem.append(flowables.Macro('canvas.restoreState()'))

    doc.build(elem, onFirstPage=drawPageFrame)

if __name__ == '__main__':
    if len(sys.argv) < 3:
    print("Usage: python jpg2pdf.py <jpgname> <pdfname>")
    exit(1)
    __jpgname = sys.argv[1]
    jpg2pdf(sys.argv[2])
2

It is important that PIL parameters are lowercase.

im.save(outfile, "PDF", quality = 100)

Quality = 100 ----will not work.

1

Here is a code that convert any file with .jpg or .JPG extension and convert into pdf, and then delete the images that have been converted. Sorry the comments are in french.

import os #necessaire pouvoir supprimer l'image une fois converti et parcourir les fichers dans le dossier
from fpdf import FPDF #necessaire pour convertir les jpg en pdf


for file in os.listdir(): # pour chaque fichiers dans le dossier dans lequel se trouve ce fichier python
if file.endswith(".jpg") or file.endswith(".JPG"): #permet de selectionner les fichers avec l'extension .jpg ou .JPG
    img=os.path.join(file) #convertie le nom du fichier en variable
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.image('%s'%img, 3,3,204 ) # les chiffres permettent de positionner l'image sur le pdf : 3mm de la gauche, 3mm du haut, et 204 mm de la gauche pour la fin de l'image
    img2=img[:-4] #supprime les 4 dernières lettres du nom du ficher, à savoir '.jpg' ou '.JPG'
    pdf.output('%s.pdf'%img2,'F') #convertie en pdf
    os.remove('%s'%img) #supprime les fichier jpg ou JPG
0

You might need to use:

import PIL
import PIL.Image

filename = 'filename'
im = PIL.Image.open(filename)

newfilename = 'path.pdf'
PIL.Image.Image.save(newfilename,outfile, "PDF", resoultion = 100.0)

I'm using windows and I used pip to install PIL. For some reason it switched to PIL.Image.Image

1
  • 1
    I just checked the newest documentation, it looks like it's cleared up where you need PIL.Image.Image.save(filename, format = ' '). Commented Jun 11, 2015 at 20:38
0

A complete example here:

import os
import PIL.Image

def img2pdf(fname):
    filename = fname
    name = filename.split('.')[0]
    im = PIL.Image.open(filename)
    if not os.path.exists('im2pdf_output'):
        os.makedirs('im2pdf_output')
    newfilename = ''.join(['im2pdf_output/',name,'.pdf'])
    PIL.Image.Image.save(im, newfilename, "PDF", resolution = 100.0)
    print("processed successfully: {}".format(newfilename))

files = [f for f in os.listdir('./') if f.endswith('.jpg')]
for fname in files:
    img2pdf(fname)
-1

The correct usage of save is:

PIL.Image.Image.save(im, newfilename, "PDF", resolution = 100.0)

example:

path='v:/dev/python/mooc/'
filename = path + '2016_a_milano_001.JPG'
im = PIL.Image.open(filename)
newfilename = path+ 'r.pdf'
PIL.Image.Image.save(im, newfilename, "PDF", resoultion=100.0)
1
  • That usage is not "more correct" than im.save(newfilename, "PDF").
    – Manur
    Commented Dec 7, 2018 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.