Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PDF from a list of images

Tags:

python

pdf

Is there any practical way to create a PDF from a list of images files, using Python?

In Perl I know that module. With it I can create a PDF in just 3 lines:

use PDF::FromImage; ... my $pdf = PDF::FromImage->new; $pdf->load_images(@allPagesDir); $pdf->write_file($bookName . '.pdf'); 

I need to do something very similar to this, but in Python. I know the pyPdf module, but I would like something simple.

like image 214
macabeus Avatar asked Dec 06 '14 02:12

macabeus


2 Answers

Install FPDF for Python:

pip install fpdf 

Now you can use the same logic:

from fpdf import FPDF pdf = FPDF() # imagelist is the list with all image filenames for image in imagelist:     pdf.add_page()     pdf.image(image,x,y,w,h) pdf.output("yourfile.pdf", "F") 

You can find more info at the tutorial page or the official documentation.

like image 61
Ilya Vinnichenko Avatar answered Oct 05 '22 15:10

Ilya Vinnichenko


The best method to convert multiple images to PDF I have tried so far is to use PIL purely. It's quite simple yet powerful:

from PIL import Image  images = [     Image.open("/Users/apple/Desktop/" + f)     for f in ["bbd.jpg", "bbd1.jpg", "bbd2.jpg"] ]  pdf_path = "/Users/apple/Desktop/bbd1.pdf"      images[0].save(     pdf_path, "PDF" ,resolution=100.0, save_all=True, append_images=images[1:] ) 

Just set save_all to True and append_images to the list of images which you want to add.

You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'. The solution is here Error while saving multiple JPEGs as a multi-page PDF

Note:Install the newest PIL to make sure save_all argument is available for PDF.

like image 22
ilovecomputer Avatar answered Oct 05 '22 13:10

ilovecomputer