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, JSONtoPDF.py, that shows how to use xtopdf to convert JSON data to PDF:

# JSONToPDF.py

# This program shows how to convert JSON input to PDF output.
# Author: Vasudev Ram - http://www.dancingbison.com
# Copyright 2014 Vasudev Ram - http://www.dancingbison.com
# This program is part of the xtopdf toolkit:
#     https://bitbucket.org/vasudevram/xtopdf

import sys
import json
from PDFWriter import PDFWriter

def error_exit(message):
    sys.stderr.write(message)
    sys.exit(1)

def JSONtoPDF(json_data):
    # Get the data values from the JSON string json_data.
    try:
        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.
    try:
        with PDFWriter(pdf_filename) as pw:
            pw.setFont(font_name, font_size)
            pw.setHeader(header)
            pw.setFooter(footer)
            for line in lines:
                pw.writeLine(line)
    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 - http://google.com/search?q=xtopdf', \
        'lines': lis \
        }
    json_data = json.dumps(data)
    JSONtoPDF(json_data)
    
def main():
    testJSONtoPDF() 

if __name__ == '__main__':
    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 JSONtoPDF.py:


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: