Peewee => PDF
Peewee is a small, expressive ORM for Python, created by Charles Leifer.
After trying out Peewee a bit, I thought of writing another application of xtopdf (my Python toolkit for PDF creation), to publish Peewee data to PDF. I used an SQLite database underlying the Peewee ORM, but it also supports MySQL and PostgreSQL, per the docs. Here is the program, in file PeeweeToPDF.py:
# PeeweeToPDF.py # Purpose: To show basics of publishing Peewee ORM data to PDF. # Requires: Peewee ORM and xtopdf. # Author: Vasudev Ram # Copyright 2016 Vasudev Ram # Web site: https://vasudevram.github.io # Blog: http://jugad2.blogspot.com # Product store: https://gumroad.com/vasudevram from peewee import * from PDFWriter import PDFWriter def print_and_write(pw, s): print s pw.writeLine(s) # Define the database. db = SqliteDatabase('contacts.db') # Define the model for contacts. class Contact(Model): name = CharField() age = IntegerField() skills = CharField() title = CharField() class Meta: database = db # Connect to the database. db.connect() # Drop the Contact table if it exists. db.drop_tables([Contact]) # Create the Contact table. db.create_tables([Contact]) # Define some contact rows. contacts = ( ('Albert Einstein', 22, 'Science', 'Physicist'), ('Benjamin Franklin', 32, 'Many', 'Polymath'), ('Samuel Johnson', 42, 'Writing', 'Writer') ) # Save the contact rows to the contacts table. for contact in contacts: c = Contact(name=contact[0], age=contact[1], \ skills=contact[2], title=contact[3]) c.save() sep = '-' * (20 + 5 + 10 + 15) # Publish the contact rows to PDF. with PDFWriter('contacts.pdf') as pw: pw.setFont('Courier', 12) pw.setHeader('Demo of publishing Peewee ORM data to PDF') pw.setFooter('Generated by xtopdf: slides.com/vasudevram/xtopdf') print_and_write(pw, sep) print_and_write(pw, "Name".ljust(20) + "Age".center(5) + "Skills".ljust(10) + "Title".ljust(15)) print_and_write(pw, sep) # Loop over all rows queried from the contacts table. for contact in Contact.select(): print_and_write(pw, contact.name.ljust(20) + str(contact.age).center(5) + contact.skills.ljust(10) + contact.title.ljust(15)) print_and_write(pw, sep) # Close the database connection. db.close()I could have used Python's namedtuple feature instead of tuples, but did not do it for this small program.
I ran the program with:
python PeeweeToPDF.pyHere is a screenshot of the output as seen in Foxit PDF Reader (click image to enlarge):
- Enjoy.
- Vasudev Ram - Online Python training and consulting Get updates on my software products / ebooks / courses. Jump to posts: Python DLang xtopdf Subscribe to my blog by email My ActiveState recipes FlyWheel - Managed WordPress Hosting
No comments:
Post a Comment