Table of Contents
You may have come across many doubts and confusions in the article. We guarantee that all your queries will be resolved via the Python 3 Django weasyprint Example to Convert HTML5 Template to PDF Document Using django-weasyprint Library article.
What is WeasyPrint?
WeasyPrint is a visual rendering engine for HTML and CSS that can export to PDF. It aims to support web standards for printing. WeasyPrint is free software made available under a BSD license.

Python 3 Django weasyprint Example to Convert HTML5 Template to PDF Document Using django-weasyprint Library
pip install django-weasyprint
app.py
import functools
from django.conf import settings
from django.views.generic import DetailView
from django_weasyprint import WeasyTemplateResponseMixin
from django_weasyprint.views import CONTENT_TYPE_PNG, WeasyTemplateResponse
class MyModelView(DetailView):
# vanilla Django DetailView
model = MyModel
template_name = 'mymodel.html'
class CustomWeasyTemplateResponse(WeasyTemplateResponse):
# customized response class to change the default 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(django_url_fetcher, ssl_context=context)
class MyModelPrintView(WeasyTemplateResponseMixin, MyModelView):
# output of MyModelView 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 MyModelDownloadView(WeasyTemplateResponseMixin, MyModelView):
# suggested filename (is required for attachment/download!)
pdf_filename = 'foo.pdf'
class MyModelImageView(WeasyTemplateResponseMixin, MyModelView):
# generate a PNG image instead
content_type = CONTENT_TYPE_PNG
# dynamically generate filename
def get_pdf_filename(self):
return 'foo-{at}.pdf'.format(
at=timezone.now().strftime('%Y%m%d-%H%M'),
)
Read Also: Django FusionChart.js Example to Draw Colorful Charts in Browser Using HTML5
Final Thoughts
We hope the Python 3 Django weasyprint Example to Convert HTML5 Template to PDF Document Using django-weasyprint Library article clears up your doubts and confusion. See you again in a good article. Thanks.