Convert Python images from Jpeg to PDF

I am trying to convert a jpeg file with 200 dpi to a pdf file, however, when I save the file in PDF format, I think it changes the dpi to 72 and thus makes the image larger. I had a similar problem when I initially tried to scale the jpeg image to a smaller size and was able to solve this by specifying dpi when saving 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, dpi is not like the difference, and I get an image that is larger than my original, it looks like it has a lower dpi. Is there a way to provide consistent resolution when converting from Jpeg to PDF using PIL? Or is there a better way for me to do this?

This is what I have to convert the file directory 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)

!

+5
7

CHANGES PIL 1.1.7 :

  • ​​ PDF.

    : PdfImagePlugin.py 1.1.6, Ubuntu, ""
    . , PDF PDF 72dpi.

, :

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

(, Ubuntu).

+11

reportlab .

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])
+6

, PIL .

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

= 100 ---- .

+2

Here is the code that converts any file with the extension .jpg or .JPG and converts to PDF, and then deletes the images that were converted. Sorry, the comments are written 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
+1
source

You may 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 use windows and I used pip to install PIL. For some reason, he switched to PIL.Image.Image

0
source

Proper use of conservation:

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

Full example:

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

All Articles