Monday, September 9, 2013

Publish MongoDB data to PDF with xtopdf

By Vasudev Ram

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


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

Here is the MongoDBToPDF program:

# Program to publish MongoDB data to PDF using xtopdf.
# Author: Vasudev Ram -
# 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.{"Name": "Tom", "Age": 10}){"Name": "Dick", "Age": 20}){"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.

# 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"]))



Save the above program as .

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

You can now run the program with:
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: