There are many ways for generating PDF in python. In this post, I will be presenting PDF files generation with xhtml2pdf.
xhtml2pdf: xhtml2pdf is a HTML/CSS to PDF converter written in Python and therefore platform independent. xhtml2pdf supports for frameworks like Django and simple integration into Python programs. It is also usable as stand alone command line tool.
pisa: pisa is a html2pdf converter using the ReportLab Toolkit, the HTML5lib and pyPdf.
Install xhtml2pdf: You can install it with pip using the command - pip install xhtml2pdf
Next start writing a view that generates a PDF document from HTML content. Consider using the cStringIO library as a temporary holding place for your PDF file. The cStringIO library provides a file-like object interface that is particularly efficient.
from xhtml2pdf import pisa import cStringIO as StringIO def html_to_pdf(request): # Write your data here. html = """
from xhtml2pdf import pisa import cStringIO as StringIO from django.template.loader import get_template from django.template import Context def html_to_pdf_directly(request): template = get_template("template_name.html") context = Context({'pagesize':'A4'}) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html), dest=result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else: return HttpResponse('Errors')
The above code converts given HTML template to PDF File.
Micropyramid is a software development and cloud consulting partner for enterprise businesses across the world. We work on python, Django, Salesforce, Angular, Reactjs, React Native, MySQL, PostgreSQL, Docker, Linux, Ansible, git, amazon web services. We are Amazon and salesforce consulting partner with 5 years of cloud architect experience. We develop e-commerce, retail, banking, machine learning, CMS, CRM web and mobile applications.
Django-CRM :Customer relationship management based on Django
Django-blog-it : django blog with complete customization and ready to use with one click installer Edit
Django-webpacker : A django compressor tool
Django-MFA : Multi Factor Authentication
Docker-box : Web Interface to manage full blown docker containers and images
More...