DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Reportlab: Converting Hundreds of Images Into PDFs

Reportlab: Converting Hundreds of Images Into PDFs

Mike Driscoll user avatar by
Mike Driscoll
·
Apr. 24, 12 · Interview
Like (0)
Save
Tweet
Share
6.75K Views

Join the DZone community and get the full member experience.

Join For Free

I was recently asked to convert a few hundred images into PDF pages. A friend of mine draws comics and my brother wanted to be able to read them on a tablet. Alas, if you had a bunch of files named something like this:

'Jia_01.Jpg', 'Jia_02.Jpg', 'Jia_09.Jpg', 'Jia_10.Jpg', 'Jia_11.Jpg', 'Jia_101.Jpg'


the Android tablet would reorder them into something like this:


'Jia_01.Jpg', 'Jia_02.Jpg', 'Jia_09.Jpg', 'Jia_10.Jpg', 'Jia_101.Jpg', 'Jia_11.Jpg'


And it got pretty confusing the more files you had that were out of order. Sadly, even Python sorts files this way. I tried using the glob module on them directly and then sorting the result and got the exact same issue. So the first thing I had to do was find some kind of sorting algorithm that could sort them correctly. It should be noted that Windows 7 can sort the files correctly in its file system, even though Python cannot.

After a little searching on Google, I found the following script on StackOverflow:

import re
 
#----------------------------------------------------------------------
def sorted_nicely( l ):
    """
    Sort the given iterable in the way that humans expect.
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)

That worked perfectly! Now I just had to find a way to put each comic page on their own PDF page. Fortunately, the reportlab library makes this pretty easy to accomplish. You just need to iterate over the images and insert them one at a time onto a page. It’s easier to just look at the code, so let’s do that:

import glob
import os
import re
 
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreak
from reportlab.lib.units import inch
 
#----------------------------------------------------------------------
def sorted_nicely( l ):
    """
    # http://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python
 
    Sort the given iterable in the way that humans expect.
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)
 
#----------------------------------------------------------------------
def create_comic(fname, front_cover, back_cover, path):
    """"""
    filename = os.path.join(path, fname + ".pdf")
    doc = SimpleDocTemplate(filename,pagesize=letter,
                            rightMargin=72,leftMargin=72,
                            topMargin=72,bottomMargin=18)
    Story=[]
    width = 7.5*inch
    height = 9.5*inch
 
    pictures = sorted_nicely(glob.glob(path + "\\%s*" % fname))
 
    Story.append(Image(front_cover, width, height))
    Story.append(PageBreak())
 
    x = 0
    page_nums = {100:'%s_101-200.pdf', 200:'%s_201-300.pdf',
                 300:'%s_301-400.pdf', 400:'%s_401-500.pdf',
                 500:'%s_end.pdf'}
    for pic in pictures:
        parts = pic.split("\\")
        p = parts[-1].split("%s" % fname)
        page_num = int(p[-1].split(".")[0])
        print "page_num => ", page_num
 
        im = Image(pic, width, height)
        Story.append(im)
        Story.append(PageBreak())
 
        if page_num in page_nums.keys():
            print "%s created" % filename
            doc.build(Story)
            filename = os.path.join(path, page_nums[page_num] % fname)
            doc = SimpleDocTemplate(filename,
                                    pagesize=letter,
                                    rightMargin=72,leftMargin=72,
                                    topMargin=72,bottomMargin=18)
            Story=[]
        print pic
        x += 1
 
    Story.append(Image(back_cover, width, height))
    doc.build(Story)
    print "%s created" % filename
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    path = r"C:\Users\Mike\Desktop\Sam's Comics"
    front_cover = os.path.join(path, "FrontCover.jpg")
    back_cover = os.path.join(path, "BackCover2.jpg")
    create_comic("Jia_", front_cover, back_cover, path)

Let’s break this down a bit. As usual, you have some necessary imports that are required for this code to work. You’ll note we also have that sorted_nicely function that we talked about earlier is in this code too. The main function is called create_comic and takes four arguments: fname, front_cover, back_cover, path. If you have used the reportlab toolkit before, then you’ll recognize the SimpleDocTemplate and the Story list as they’re straight out of the reportlab tutorial.

Anyway, you loop over the sorted pictures and add the image to the Story along with a PageBreak object. The reason there’s a conditional in the loop is because I discovered that if I tried to build the PDF with all 400+ images, I would run into a memory error. So I broke it up into a series of PDF documents that were 100 pages or less. At the end of the document, you have to call the doc object’s build method to actually create the PDF document.

Now you know how I ended up writing a whole slew of images into multiple PDF documents. Theoretically, you could use PyPdf to knit all the resulting PDFs together into one PDF, but I didn’t try it. You might end up with another memory error. I’ll leave that as an exercise for the reader.

Source Code

  • comic_maker.zip
  • comic_maker.tar

 

PDF Sorting algorithm Document Sort (Unix) Memory (storage engine) Python (language) Build (game engine) Object (computer science)

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Monolithic First
  • Custom Validators in Quarkus
  • Front-End Troubleshooting Using OpenTelemetry
  • How To Build a Spring Boot GraalVM Image

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: