django-wkhtmltopdf

3.4.0 · active · verified Fri Apr 17

django-wkhtmltopdf is a Django library that allows you to render HTML templates to PDF documents using the external `wkhtmltopdf` utility. It provides class-based views and utility functions for PDF generation within Django projects. The current version is 3.4.0, and it maintains a steady release cadence with a focus on stability and compatibility with newer Django versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a PDF view using `PDFTemplateView`. Ensure the `wkhtmltopdf` binary is installed on your system and its path is set in `WKHTMLTOPDF_CMD` in your Django settings. It renders `hello_pdf.html` into a downloadable PDF.

import os
from django.conf import settings
from django.urls import path
from django.views.generic import TemplateView
from wkhtmltopdf.views import PDFTemplateView


# Minimal Django settings for demonstration
settings.configure(
    DEBUG=True,
    INSTALLED_APPS=[
        'django.contrib.staticfiles',
        'wkhtmltopdf'
    ],
    TEMPLATES=[
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(os.path.dirname(__file__), 'templates')],
            'APP_DIRS': True,
        },
    ],
    STATIC_URL='/static/',
    WKHTMLTOPDF_CMD=os.environ.get('WKHTMLTOPDF_CMD', '/usr/local/bin/wkhtmltopdf') # IMPORTANT: Set this to your wkhtmltopdf binary path
)

# Create a dummy template file for the quickstart
os.makedirs(os.path.join(os.path.dirname(__file__), 'templates'), exist_ok=True)
with open(os.path.join(os.path.dirname(__file__), 'templates', 'hello_pdf.html'), 'w') as f:
    f.write('<h1>Hello, PDF!</h1><p>Generated by django-wkhtmltopdf.</p>')

urlpatterns = [
    path(
        'pdf-view/', 
        PDFTemplateView.as_view(
            template_name='hello_pdf.html', 
            filename='my_document.pdf',
            header_html='<p>Header</p>',
            footer_html='<p>Footer</p>',
            show_as_attachment=True,
            cmd_options={'enable-local-file-access': True}
        ),
        name='pdf_view'
    ),
    path(
        'html-view/', 
        TemplateView.as_view(template_name='hello_pdf.html'), 
        name='html_view'
    )
]

# To run this minimal example (for testing):
# from django.core.management import execute_from_command_line
# if __name__ == '__main__':
#     execute_from_command_line(['manage.py', 'runserver', '--noreload'])

# To access: Navigate to /pdf-view/ after setting up Django and wkhtmltopdf

view raw JSON →