SaltyCrane Blog — Notes on JavaScript and web development

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

Comments