Python - Saving Image As PDF



Description

pdf stands for portable document format.pdf is type of file format where we can interchange data in unchangable format. The pdf file may contain anything that includes text or images.To open a pdf file, we need to have Adobe acrobat reader.

python with Image Library supports saving the image into pdf.We can open any kind of image and save it as pdf.Before saving it as pdf, make sure that adobe acrobat reader has been installed or else the pdf file may become useless.

For saving the image to pdf we need to import Image . Image is the fundamental module for loading and opening the image.

Let us take the below image and will try to convert the image to pdf.

pdf

First import the Image module and ImageFilter modules and then open the image with open method in Image.ImageFilter contains the various attributes that are used to blue the image.Make sure to give the complete path of the image where it has been placed.
import os
from PIL import Image
filename = 'flower2.jpg'
im = Image.open(filename)

Creating the filename from the image name
newfile_pdf = os.path.splitext(filename)[0] newfile_pdf = newfile_pdf + ".pdf"

Save the image file with save method from Image module and in additional two more arguments has to be passed in order to save the image file as pdf.
im.save(newfile_pdf, "pdf", resoultion = 100.0)

Syntax

Following is the syntax of functions been used.
# Import Pillow:
from PIL import Image
newfile_pdf = os.path.splitext(filename)[0]
newfile_pdf = newfile_pdf + ".pdf"

Parameters

With the Image library, we will first remove(split) the existing extension and concatenate the pdf to the base filename.
Note:If image is in same directory where your python program resides, you can give the image name itself. If the image resides in some other directory, you are supposed to define the complete path of the image.

Return value

The new image gets created with pdf format in the current directory.
Note: Adobe Acrobat Reader software has to be installed for opening the pdf file.

Example

The following example shows how to convert the image to pdf format.
import os
from PIL import Image
filename = 'flower2.jpg'
im = Image.open(filename)
newfile_pdf = os.path.splitext(filename)[0]
newfile_pdf = newfile_pdf + ".pdf"
im.save(newfile_pdf, "pdf", resoultion = 100.0)


Advertisements