Skip to main content

Django-WeasyPrint

Build Coverage PyPI Download PyPI Python Versions PyPI License

A Django WeasyPrint integration providing class-based view and response class for generating PDF from templates.

Installation

Install and update using pip:

pip install -U django-weasyprint

WeasyPrint is automatically installed as a dependency of this package. If you run into any problems be sure to check their install instructions for help!

Tip: In version 53 WeasyPrint switched to pydyf as PDF generator instead of Cairo. With that change PNG output was dropped and you might encounter other changes in the generated PDF.

You can continue using WeasyPrint/Cairo by installing django-weasyprint 1.x!

Usage

Use WeasyTemplateView as class based view base class or the mixin WeasyTemplateResponseMixin on a TemplateView (or subclass thereof).

Example

# views.py
import functools

from django.conf import settings
from django.views.generic import DetailView

from django_weasyprint import WeasyTemplateResponseMixin
from django_weasyprint.views import WeasyTemplateResponse
from django_weasyprint.utils import DjangoURLFetcher

class MyDetailView(DetailView):
    # vanilla Django DetailView
    template_name = 'mymodel.html'

class CustomURLFetcher(DjangoURLFetcher):
    # rewrite requests for CDN URLs to file path in STATIC_ROOT to use local file
    def fetch(self, url, headers=None):
        cloud_storage_url = 'https://s3.amazonaws.com/django-weasyprint/static/'
        if url.startswith(cloud_storage_url):
            url = 'file://' + url.replace(cloud_storage_url, settings.STATIC_URL)
        return super().fetch(url, headers)

class CustomWeasyTemplateResponse(WeasyTemplateResponse):
    # use custom URLFetcher in response class
    url_fetcher_class = CustomURLFetcher

    # customized response class to pass a kwarg to already custom URLFetcher
    def get_url_fetcher(self, *args, **kwargs):
        # disable host and certificate check
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        kwargs['ssl_context'] = context
        return self.url_fetcher_class(*args, **kwargs)

class PrintView(WeasyTemplateResponseMixin, MyDetailView):
    # output of MyDetailView rendered as PDF with hardcoded CSS
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'css/app.css',
    ]
    # show pdf in-line (default: True, show download dialog)
    pdf_attachment = False
    # custom response class with CustomURLFetcher and ssl_context
    response_class = CustomWeasyTemplateResponse

class DownloadView(WeasyTemplateResponseMixin, MyDetailView):
    # suggested filename (is required for attachment/download!)
    pdf_filename = 'foo.pdf'
    # set PDF variant to 'pdf/ua-1' (see weasyprint.DEFAULT_OPTIONS)
    pdf_options = {'pdf_variant': 'pdf/ua-1'}

class DynamicNameView(WeasyTemplateResponseMixin, MyDetailView):
    # dynamically generate filename
    def get_pdf_filename(self):
        return 'foo-{at}.pdf'.format(
            at=timezone.now().strftime('%Y%m%d-%H%M'),
        )

def simple_function_view(request):
    # minimal boilerplate usage :)
    return WeasyTemplateResponse(request, 'example.html', context={})
# tasks.py
from celery import shared_task
from django.template.loader import render_to_string

from django_weasyprint.utils import DjangoURLFetcher

@shared_task
def generate_pdf(filename='mymodel.pdf'):
    weasy_html = weasyprint.HTML(
        string=render_to_string('mymodel.html'),
        url_fetcher=DjangoURLFetcher(),
        base_url='file://',
    )
    weasy_html.write_pdf(filename)
<!-- mymodel.html -->
<!doctype html>
<html>
    <head>
        <!-- Use "static" template tag and configure STATIC_URL as usual. -->
        <link rel="stylesheet" href="{% static 'css/app.css' %}" />
    </head>
    <body>
        Hello PDF-world!
    </body>
</html>

Settings

By default WeasyTemplateResponse determines the base_url for weasyprint.HTML and weasyprint.CSS automatically using Django's request.build_absolute_uri().

To disable that set WEASYPRINT_BASEURL to a fixed value, e.g.:

# Disable prefixing relative URLs with request.build_absolute_uri().
# Instead, handle them as absolute file paths.
WEASYPRINT_BASEURL = '/'

Changelog

See CHANGELOG.md

Metadata

Release files for django-weasyprint 2.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-weasyprint 2.6.0
File Size Uploaded
django_weasyprint-2.6.0.tar.gz 15.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-weasyprint 2.6.0
File Interpreter ABI Platform
django_weasyprint-2.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 24.8 kB

Release files / django_weasyprint-2.6.0.tar.gz

Download URL django_weasyprint-2.6.0.tar.gz
Size 15.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ec69834de0c1b416bdc9a9a6aaf72070d7a0072ce38df9cc9296d123ffcf5e28
BLAKE2b-256 checksum
How to use checksums
aea11d002b74459ad85645d2ef162fd6f8894f4b155e53689234c39f62f9b17b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / django_weasyprint-2.6.0-py3-none-any.whl

Download URL django_weasyprint-2.6.0-py3-none-any.whl
Size 9.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31d5bf5d5b1520b9e7d916a3c554b7c66d3a411871e1d02ea70267117e5510b0
BLAKE2b-256 checksum
How to use checksums
acf43109126fb65818416e268d0c2ff0f95bc8f2a6fd798c20647dc7028ce8c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release history Release notifications | RSS feed

This release

2.6.0 This release

2 release files

2.5.0

2 release files

2.4.1

2 release files

2.4.0

2 release files

2.3.1

2 release files

2.3.0

2 release files

2.2.2

2 release files

2.2.1

2 release files

2.2.0

2 release files

2.1.0

2 release files

2.0.0

2 release files

1.1.0

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.6.0

2 release files

0.5.5

1 release file

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page