Welcome, guest | Sign In | My Account | Store | Cart

This recipe show the basic steps needed to convert JSON input to PDF output, using Python and xtopdf, a PDF creation toolkit. xtopdf is itself written in Pytho, and uses the ReportLab toolkit internally.

We set up some needed values, such as the output PDF file name, the font name and size, the header and footer, and the input lines for the body of the PDF output; all these values are passed in JSON format (in a single dictionary) to a function that uses those values to generate a PDF file with the desired content.

The code is intentionally kept simple so as to require the least amount of code needed to demonstrate the techniques involved. But it can be generalized or extended to more complex situations.

Python, 52 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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()

This recipe can be useful if you have (or can arrange to have) data in JSON format and you want to easily output it to PDF, with headers and footers on each page, and pagination. Line-oriented or structured text output or business reports, where the input is available in JSON format (or can be converted to JSON format), will benefit from this recipe.