开发者

Using Pisa to write a pdf to disk

开发者 https://www.devze.com 2022-12-31 05:57 出处:网络
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 .pd开发者_JS百科f version file at sp

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 .pd开发者_JS百科f version file at specified points in time and save it in a uploads directory, so there is no browser interaction. Is this possible?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消