Skip to content

Instantly share code, notes, and snippets.

@pratheekhegde
Created September 23, 2016 18:00
Show Gist options
  • Select an option

  • Save pratheekhegde/c973a107933f30b9ead4973a7516113e to your computer and use it in GitHub Desktop.

Select an option

Save pratheekhegde/c973a107933f30b9ead4973a7516113e to your computer and use it in GitHub Desktop.
Generate PDF with Python using PhantomJS and Jinga
#!/usr/bin/env python
'''
Created on 22 Sep 2016
@author: phegde
'''
from subprocess import call
#from string import Template
from jinja2 import Environment, FileSystemLoader
import codecs
import json
import os
def generate_pdf(dataJson, templateName):
try:
#jinja template engine
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template(templateName)
substitutedTemplate = template.render(dataJson)
#file names
tempHTML = dataJson.get('fullName')+' - '+templateName+'-temp.html'
pdfFileName = dataJson.get('fullName')+' - '+templateName
FILE = open(os.path.join('./temp', tempHTML), "wb")
FILE.write(substitutedTemplate)
FILE.close()
#generate pdf
call(["phantomjs", "rasterize.js", './temp/'+tempHTML, pdfFileName+'.pdf'])
#dispatch the file
#delete the temp pdf
os.remove('./temp/'+tempHTML)
except Exception as e:
print e
if __name__ == "__main__":
#read dummy json
profileData = open('profile.json')
data = json.load(profileData)
dataJson = data.get('userProfile')
templateName = 'profile_snapshot.html'
generate_pdf(dataJson,templateName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment