Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

How to convert a PNM file to PDF with Python

  • Install the Python Imaging Library (PIL)
    On Ubuntu/Debian, use:
    sudo apt-get install python-imaging
  • Create a file called convert_pnm_to_pdf.py:
    import Image
    import os
    import sys
    
    filename = sys.argv[1]
    try:
        newfilename = os.path.splitext(filename)[0] + ".pdf"
        Image.open(filename).save(newfilename)
        print "Converted " + newfilename
    except IOError:
        print "Cannot convert" + newfilename
    
  • Run the script:
    python convert_pnm_to_pdf.py yourfile.pnm
    A PDF file named yourfile.pdf will be created

The PIL also supports many other file formats including BMP, GIF, JPEG, PNG, and TIFF. For more information, see the Python Imaging Library Handbook

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Slicehost