Usage

Prepare HTML Templates

Create a Django HTML template with embedded CSS style. You can use special style attributes to format the PDF output.

For more information on the supported HTML and CSS rules see docs at https://github.com/xhtml2pdf/xhtml2pdf/blob/master/doc/source/usage.rst

You can also use custom embeddable resources like images and fonts. Put them inside Django’s STATIC_ROOT directory and make sure they are available locally on the server even if you are serving your static files from S3 or other CDN.

For now only local resources are supported.

{% extends "easy_pdf/base.html" %}

{% block extra_style %}
    <style type="text/css">
        body {
            font-family: "Helvetica", "sans-serif";
            color: #333333;
        }
    </style>
{% endblock %}

{% block content %}
    <div id="content">
        <div class="main">
            <h1>Hi there!</h1>
        </div>
    </div>
{% endblock %}

Create PDF rendering views

This part is easy. The PDF rendering view inherits from TemplateResponseMixin so it works in the same way as Django’s TemplateView. Just point it to a HTML template and define get_context_data() method to pass any extra variables to the template:

from easy_pdf.views import PDFTemplateView

class HelloPDFView(PDFTemplateView):
    template_name = 'hello.html'

    def get_context_data(self, **kwargs):
        return super(HelloPDFView, self).get_context_data(
            pagesize='A4',
            title='Hi there!',
            **kwargs
        )

Then add the view to your url config and start serving PDF files rendered from the HTML template.

urlpatterns = [
    url(r'^hello.pdf$', HelloPDFView.as_view())
]

You can also use a mixin to output PDF from Django generic views:

.. code-block:: python
class PDFUserDetailView(PDFTemplateResponseMixin, DetailView):
model = get_user_model() template_name = ‘user_detail.html’

Rendering PDF outside of Django views

See PDF rendering functions.