Omonbude Emmanuel
Software Engineer
HTML/CSS/JAVASCRIPT
PYTHON
DJANGO/DJANGO REST FRAMEWORK
NODE JS
DOCKER, AWS, KUBERNATES
FIREBASE, PostgreSQL, MySQL,Mongo DB
FLUTTER
DART
ANGULAR
TYPESCRIPT

Pdf Generation in django web framework

Omonbude Emmanuel | Jan. 20, 2024, 9:32 a.m.

88

Introduction

PDF generation is a powerful feature that enhances the functionality of web applications. Whether you're building an e-commerce platform, a content management system, or a business application, the ability to generate PDFs can add significant value. In this tutorial, we'll explore how to generate PDFs in Django using the xhtml2pdf library, which converts HTML and CSS into PDF documents.

Prerequisites

Before we start, ensure you have the following prerequisites:

  1. Basic understanding of Django and Python.
  2. A Django project set up on your local machine.
  3. Familiarity with HTML and CSS, as we'll use these for PDF templates.

Steps

1. Setting Up the Environment

First, ensure you have Django installed. If not, you can install it using pip:

pip install django

 

Next, install the xhtml2pdf library:

 

pip install xhtml2pdf

2. Creating a Django Project

If you haven't already created a Django project, you can create one using the following command:
 

django-admin startproject myproject
cd myproject

Create a new Django app within your project:

 

python manage.py startapp pdfapp

Add the new app to your project's settings.py:

 

INSTALLED_APPS = [ ... 'pdfapp', ]

 

3. Creating a Template for the PDF

Create a directory for templates in your pdfapp directory and add an HTML file that will serve as the template for your PDF:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PDF Report</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .header {
            text-align: center;
            margin-bottom: 50px;
        }
        .content {
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>{{ title }}</h1>
    </div>
    <div class="content">
        <p>{{ content }}</p>
    </div>
</body>
</html>

4. Writing the View to Generate the PDF

In your pdfapp/views.py, create a view that will render the template and generate the PDF:

from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

def pdf_view(request):
    context = {
        'title': 'Sample PDF Report',
        'content': 'This is a sample PDF generated from HTML and CSS using Django and xhtml2pdf.'
    }
    return render_to_pdf('pdfapp/pdf_template.html', context)

 

5. Configuring URLs

Add a URL pattern for your PDF view in pdfapp/urls.py:

from django.urls import path
from .views import pdf_view

urlpatterns = [
    path('pdf/', pdf_view, name='pdf_view'),
]

Include this in your main project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('pdfapp/', include('pdfapp.urls')),
]

 

6. Testing the PDF Generation

Run your Django development server:

python manage.py runserver 

 

Navigate to http://127.0.0.1:8000/pdfapp/pdf/ in your web browser. You should see a generated PDF document based on the HTML template.

Conclusion

Generating PDFs in a Django application is straightforward with the help of the xhtml2pdf library. By converting HTML and CSS to PDFs, you can create complex, styled documents that are easy to maintain and update. This tutorial covered setting up your environment, creating templates, writing views, and configuring URLs to generate and serve PDFs in your Django application.

 

© 2024 Omonbude Emmanuel

Omonbude Emmanuel