Python + Postscript = Profit!

While setting up the computing environment for the “Introduction to Computational Quantum Nanoelectronics” tutorial at the APS March Meeting, I came across the problem that I needed to generate 150 chits of paper with login information on them. While all the login info was available in plain text form, this didn’t really lend itself well to easy printing. Given the number of chits we would have to generate I didnt really feel like manually copy/pasting/formatting the contents of the text file using word processing software. A colleague suggested that I take a look at Postscript, which is a language for creating vector graphics. It’s pretty bare-bones in terms of the features it offers (it’s mainly meant as the output of sophisticated document processors such as TeX), but getting a few lines of text layed out on a page it’s perfect. The Python snippet below shows how simple it is to write a simple Postscript generator.

import sys

postscript_header = """

    /Inconsolata findfont
    50 scalefont

    %%Pages: {0}

postscript_page = """
    %%Page {0} {0}
      90 rotate 0 -595 translate

    50 400 moveto
    (user: {1}) show
    50 300 moveto
    (password: {2}) show

pages = [postscript_header]
for pagenum, line in enumerate(sys.stdin, 1):
    user, passwd = line.split()
    pages.append(postscript_page.format(pagenum, user, passwd))

# now we know the number of pages, format the page header
pages[0] = pages[0].format(pagenum)

The above snippet takes username/password pairs from stdin and and writes a postscript document to stdout. It displays a single username/password per page in 50pt Inconsolata1 and oriented landscape. This can be read using most standard document viewers, and when printing the output can be compacted somewhat by printing several logical pages per physical page. The raw postscript can also be converted into other formats such as PDF, which is useful as the fonts are embedded directly into the document and mean that the document can be easily shared.

Now that I’ve seen just how easy it is to generate proper documents with Python and postscript I’m sure that I’ll be integrating it into my workflow more often!

  1. This font is advantageous for username/password combinations as it distinguishes zeros from O’s by putting a slash through the former. ↩︎