How to create sample pdf file using Python and django?


Process :1

step 1: run this cmd:  pip install reportlab


step2: Create a file with below code.


from reportlab.pdfgen import canvas

c=canvas.Canvas("mypdf.pdf")
c.drawString(150,180,"This is sample pdf")
c.save()


Process :2

Python : 2.7
Django :1.11

1.pip install xhtml2pdf html5lib pypdf html5lib==1.0b8

2.create python file pdfgenerator.py

import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template,render_to_string
from django.template import Context
from django.http import HttpResponse
from cgi import escape
# from django.shortcuts import renderfrom django.shortcuts import render_to_response

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(Context)
    html = template.render(context_dict)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

place the python in  pdfgenerator.py file

 3.Create method in views.py

Note:

from app.pdfgenerator import render_to_pdf 

def pdf_page(request,pk):

    print "pdf print...."
        context = {'pagesize':'A4','test':test}
        return render_to_pdf('mytemplate.html',context)


4.create mytemplate.html in templates directory.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p> Html to PDF generator.....with python 2.7 and django 1.11</p>
</body>
</html>      
 

5. add the below url in url.py

url(r'^pdf_page/$', views.pdf_page,name='pdf_page'),


Done.......


No comments:

Post a Comment