Sunday, December 15, 2013

[xtopdf] PDFWriter now has context manager support

By Vasudev Ram

I've added context manager support to the PDFWriter class in xtopdf, my Python toolkit for PDF creation. This means that you can now use the PDFWriter class in Python with statements.

Here is an example, in the program test_pdfwriter.py:
# test_pdfwriter.py

from PDFWriter import PDFWriter

with PDFWriter("test_pdfwriter.pdf") as pw:

    pw.setFont("Courier", 12)
    pw.setHeader("Input: test_pdfwriter.py Output: test_pdfwriter.pdf")
    pw.setFooter("Generated by xtopdf: http://bit.ly/xtopdf")

    with open("test_pdfwriter.py") as in_fil:
        for lin in in_fil:
            pw.writeLine(lin)

And here is the output of making test_pdfwriter.py eat its own dog food, so to speak (click screenshot to enlarge):


- Vasudev Ram - Dancing Bison Enterprises

Read other posts about xtopdf or Python on my blog.

Contact Page



1 comment:

Vasudev Ram said...

Reddit user rcfox commented on the post (on Reddit), that contextlib can be useful for when you want to easily add context manager support to something that doesn't have it.