Monday, September 9, 2013

Publish MongoDB data to PDF with xtopdf


By Vasudev Ram

This program, MongoDBToPDF.py, is a demo of how to publish MongoDB (Wikipedia) data to PDF, using my xtopdf toolkit for PDF creation from other data formats.

mongoDB

To run this program, you need to have Python, Reportlab, xtopdf and MongoDB installed on your system.

Here is the MongoDBToPDF program:

# MongoDBToPDF.py
# Program to publish MongoDB data to PDF using xtopdf.
# Author: Vasudev Ram - http://www.dancingbison.com
# Copyright 2013 Vasudev Ram

from PDFWriter import PDFWriter

import pymongo
from pymongo import MongoClient

# Create a PDFWriter object and set some of its fields.
pw = PDFWriter("MongoDB_data.pdf")
pw.setFont("Courier", 12)
pw.setHeader("MongoDB data to PDF")
pw.setFooter("Generated by xtopdf")

# Connect to MongoDB database.
client = pymongo.MongoClient("localhost", 27017)
db = client.test

# Create a collection.
persons = db.persons

# Add some data to it.
db.persons.save({"Name": "Tom", "Age": 10})
db.persons.save({"Name": "Dick", "Age": 20})
db.persons.save({"Name": "Harry", "Age": 30})

# Loop over the collection and print the items to the screen.
for item in db.persons.find():
    print item["Name"], item["Age"]

# Create an index on the Name field.
db.persons.create_index("Name")

# Loop over the sorted items and print them to PDF.
for item in db.persons.find().sort("Name", pymongo.ASCENDING):
    pw.writeLine(item["Name"] + " | " + str(item["Age"]))

pw.close()

# EOF

Save the above program as MongoDBToPDF.py .

Start the MongoDB server (daemon / service) if it is not already running, with:
mongod

You can now run the program with:
python MongoDBToPDF.py
The output will be in the file MongoDB_data.pdf, which you can view in any suitable PDF viewer, such as Adobe Reader or Foxit PDF Reader.

The above program does the following, broadly speaking:

- creates a PDFWriter instance
- connects to a MongoDB database
- creates a collection and populates it with some person data for the demo
- creates an index on the Name field
- sorts the data on the Name field and prints the data to PDF

According to the Wikipedia article linked above, Craigslist, SAP, Forbes, The New York Times, SourceForge, The Guardian, CERN, Foursquare and eBay are some organizations that use MongoDB.

Read all xtopdf posts on jugad2.

Read all Python posts on jugad2.

- Vasudev Ram - Dancing Bison Enterprises

Contact me




Back to (Tech) School Sale


No comments: