This is an extract of an example for use of "pisa" http://www.htmltopdf.org in "django". It shows the easiest way possible to create PDF documents just using HTML and CSS. In "index" we see the definition of the output of a form in which HTML code can be typed in and then on the fly a PDF will be created. In "ezpdf_sample" we see the use of templates and contexts. So adding PDF to your existing Django project could be just a matter of some lines of code.
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 53 54 55 56 57 58 59 60 61 62 63 64 | #! /usr/bin/python
# -*- encoding: utf-8 -*-
from django import http
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi
def index(request):
return http.HttpResponse("""
<html><body>
<h1>Example 1</h1>
Please enter some HTML code:
<form action="/download/" method="post" enctype="multipart/form-data">
<textarea name="data">Hello <strong>World</strong></textarea>
<br />
<input type="submit" value="Convert HTML to PDF" />
</form>
<hr>
<h1>Example 2</h1>
<p><a href="ezpdf_sample">Example with template</a>
</body></html>
""")
def download(request):
if request.POST:
result = StringIO.StringIO()
pdf = pisa.CreatePDF(
StringIO.StringIO(request.POST["data"]),
result
)
if not pdf.err:
return http.HttpResponse(
result.getvalue(),
mimetype='application/pdf')
return http.HttpResponse('We had some errors')
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
return http.HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
def ezpdf_sample(request):
blog_entries = []
for i in range(1,10):
blog_entries.append({
'id': i,
'title':'Playing with pisa 3.0.16 and dJango Template Engine',
'body':'This is a simple example..'
})
return render_to_pdf('entries.html',{
'pagesize':'A4',
'title':'My amazing blog',
'blog_entries':blog_entries})
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.