Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Pisa to write a pdf to disk

Tags:

django

pisa

I have pisa producing .pdfs in django in the browser fine, but what if I want to automatically write the file to disk? What I want to do is to be able to generate a .pdf version file at specified points in time and save it in a uploads directory, so there is no browser interaction. Is this possible?

like image 797
PhoebeB Avatar asked May 24 '10 19:05

PhoebeB


1 Answers

Yes it is possible. for example, using code from Greg Newman as a starter:

from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi

def write_pdf(template_src, context_dict, filename):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = open(filename, 'wb') # Changed from file to filename
    pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), result)
    result.close()

You just need to call write_pdf with a template, data in a dict and a file name.

like image 161
Nathan Avatar answered Oct 22 '22 19:10

Nathan