PDF Output - ( Django File Handling and Outputs )
Heading h2
Syntax
# views.py
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from io import BytesIO
def generate_pdf(request):
# Get the HTML template with context data
template_path = 'template.html'
context = {'myvar': 'Hello World!'}
template = get_template(template_path)
html = template.render(context)
# Create a file-like buffer to receive PDF data
buffer = BytesIO()
# Convert HTML to PDF
pisa_status = pisa.CreatePDF(
html, dest=buffer)
# Retrieve PDF from buffer and return response
if pisa_status.err:
return HttpResponse('An error occurred')
response = HttpResponse(
buffer.getvalue(), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="output.pdf"'
return response
Example
<!-- template.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ myvar }}</title>
</head>
<body>
<h1>{{ myvar }}</h1>
<p>This is an example PDF output using Django and xhtml2pdf.</p>
</body>
</html>
Output
A PDF file named output.pdf
will be generated and downloaded to the client's browser.
Explanation
Django provides various file handling and output options for web applications. In this example, we demonstrate how to generate PDF output using Django and xhtml2pdf libraries.
We use the get_template
method from django.template.loader
to get the HTML template that we want to convert to PDF. We then use BytesIO
to create a file-like object to store the generated PDF output.
We convert the HTML to PDF using pisa.CreatePDF
method from xhtml2pdf
and store it in our created buffer. Finally, we retrieve the generated PDF from the buffer and return it as an attachment to the HTTP response.
Use
Generating PDF output in web applications is a common requirement in various scenarios like generating reports, invoices, etc. Django provides various libraries and methods to handle file outputs, and xhtml2pdf is one of them.
Important Points
xhtml2pdf
is a Python library used to generate PDF output from HTML and CSS filespisa.CreatePDF
method is used to convert HTML to PDF- The
BytesIO
class is used to create a file-like object that receives the generated PDF data
Summary
In conclusion, generating PDF output in Django web applications can be achieved using libraries like xhtml2pdf. Using get_template
to get the HTML template, pisa.CreatePDF
to convert HTML to PDF, and BytesIO
to create a file-like object, we can generate PDF output and return it as an attachment in an HTTP response.