Support
Please support this website. Visit the Amazon using this affiliate link. There won't be any difference in your purchage, we will get some commission for every purchase you make.
Advertise with us
response pdf   0   32017
Generating and Returning PDF as response in Django

We might need to generate a receipt or a report in PDF format in Django app. In this article, we will see how to generate a dynamic PDF from html content and return it as a response.

Create a Django project. If you are not using virtual environment, we strongly recommend to do so.



Installing Dependencies:

Once virtual environment is ready and activated, install the below dependencies.

Django==1.9.7
pdfkit==0.6.1

For pdfkit  to work, we need wkhtmltopdf  installed in our Linux system.

sudo apt-get install wkhtmltopdf


View code:

To generate the PDF, we first need to create the HTML template which will be converted to PDF.

If its a static PDF, then it is recommended to create it once and upload on the server and provide the direct downloading link.

However if its a dynamic PDF like payment receipt or weekly report, we need to pass the data to template. For this we will use get_template method of template loader. For the sake of simplicity, we will pass user's name and date of birth to template. We convert the template to html string with variable values substituted in it and then generate the PDF from html string.

To return PDF as response, set the content_type as application/pdf in response.


views.py:

from django.template.loader import get_template
import pdfkit
from django.http import HttpResponse


def index(request):
    data = dict()
    data["name"] = "ThePythonDjango.Com"
    data["DOB"] = "Jan 10, 2015"

    template = get_template('testapp/test.html')
    html = template.render(data)
    pdf = pdfkit.from_string(html, False)

    filename = "sample_pdf.pdf"

    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    return response

 

If you hit the URL, file will be downloaded.

generating and returning pdf as response in django  



Options:
pdfkit functions accept the configuration options in dictionary format.

pdf_settings = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'no-outline': None
}

pdfkit.from_html(html_text, 'out.pdf', options=pdf_settings)
 

We can generate PDF from a URL directly, from html or from text using function pdfkit.from_url, pdfkit.from_html and pdfkit.from_text respectively.



Source Code:

A sample minimal project is available on Github.

Read more about pdfkit here.


response pdf   0   32017
0 comments on 'Generating And Returning Pdf As Response In Django'
Login to comment


Related Articles:
Python Requests Library: Sending HTTP GET and POST requests using Python
Python requests library to send GET and POST requests, Sending query params in Python Requests GET method, Sending JSON object using python requests POST method, checking response headers and response status in python requests library...
How to download large csv files in Django
How to download large csv file in Django, streaming the response, streaming large csv file in django, downloading large data in django without timeout, using django.http.StreamingHttpResponse to stream response in Django, Generating and transmitting large CSV files in django...
How to download data as CSV and Excel file in Django
How to download excel file in django, download data csv and excel file in django, excel file in python, csv and excel file in django python, download excel python-Django...
Automating PDF generation using Python reportlab module
Generating PDF using python reportlab module, Adding table to PDF using Python, Adding Pie Chart to PDF using Python, Generating PDF invoice using Python code, Automating PDF generation using Python reportlab module...
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap