Skip to main content

Django WeasyPrint integration

Project description

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 django_url_fetcher


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

def custom_url_fetcher(url, *args, **kwargs):
    # rewrite requests for CDN URLs to file path in STATIC_ROOT to use local file
    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 django_url_fetcher(url, *args, **kwargs)

class CustomWeasyTemplateResponse(WeasyTemplateResponse):
    # customized response class to pass a kwarg to URL fetcher
    def get_url_fetcher(self):
        # disable host and certificate check
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        return functools.partial(custom_url_fetcher, ssl_context=context)

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 to configure url-fetcher
    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 django_url_fetcher

@shared_task
def generate_pdf(filename='mymodel.pdf'):
    weasy_html = weasyprint.HTML(
        string=render_to_string('mymodel.html'),
        url_fetcher=django_url_fetcher,
        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

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_weasyprint-2.4.1.tar.gz (14.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_weasyprint-2.4.1-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file django_weasyprint-2.4.1.tar.gz.

File metadata

  • Download URL: django_weasyprint-2.4.1.tar.gz
  • Upload date:
  • Size: 14.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for django_weasyprint-2.4.1.tar.gz
Algorithm Hash digest
SHA256 1c776e2df7f267e853ced5f5284a3928e5e3853652ed620b8569d19dfdc5c52b
MD5 a769c02529afe3b4511644bc78555917
BLAKE2b-256 13052e98a829a28acfc2efa304506d3081d1b75d5688e3e1da3bb4cc0939d27c

See more details on using hashes here.

File details

Details for the file django_weasyprint-2.4.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_weasyprint-2.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 76d1a05bfdd9ef781d003c5dbe41014356c364522340628dfaf8e9e7214f0a35
MD5 fa85dea8b96a8de0263386827eaea813
BLAKE2b-256 daa33a49e8f5d397a8c7e1ecef41e8429d8430396c30abe83bffd9ff2c1569c3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page