Wednesday, December 10, 2014

Convert JSON to PDF with xtopdf

By Vasudev Ram

I added support for JSON as an input format to xtopdf, my Python toolkit for PDF creation.

Here is an example program,, that shows how to use xtopdf to convert JSON data to PDF:


# This program shows how to convert JSON input to PDF output.
# Author: Vasudev Ram -
# Copyright 2014 Vasudev Ram -
# This program is part of the xtopdf toolkit:

import sys
import json
from PDFWriter import PDFWriter

def error_exit(message):

def JSONtoPDF(json_data):
    # Get the data values from the JSON string json_data.
        data = json.loads(json_data)
        pdf_filename = data['pdf_filename']
        font_name = data['font_name']
        font_size = data['font_size']
        header = data['header']
        footer = data['footer']
        lines = data['lines']
    except Exception as e:
        error_exit("Invalid JSON data: {}".format(e.message))
    # Generate the PDF using the data values.
        with PDFWriter(pdf_filename) as pw:
            pw.setFont(font_name, font_size)
            for line in lines:
    except IOError as ioe:
        error_exit("IOError while generating PDF file: {}".format(ioe.message))
    except Exception as e:
        error_exit("Error while generating PDF file: {}".format(e.message))

def testJSONtoPDF():
    fil = open('the-man-in-the-arena.txt')
    lis = fil.readlines()
    data = { \
        'pdf_filename': 'the-man-in-the-arena.pdf', \
        'font_name': 'Courier', \
        'font_size': 12, \
        'header': 'The Man in the Arena', \
        'footer': 'Generated by xtopdf -', \
        'lines': lis \
    json_data = json.dumps(data)
def main():

if __name__ == '__main__':
In the example program, I used as input, the text of "The Man in the Arena", which is a well-known excerpt of a speech by Theodore Roosevelt, the 26th President of the United States.

Here is a screenshot of the PDF file created by

Here is the Wikipedia page about JSON, JavaScript Object Notation.

Here is the Wikipedia page about PDF, the Portable Document Format.
PDF became an ISO standard (ISO 32000) some years ago.

- Vasudev Ram - Dancing Bison Enterprises - Python training and consulting

Signup for email about new Python-related products from me.

Contact Page

No comments: