Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

Using Python Weasyprint Generate HTML to PDF in Django

2022-07-25

In most of the web development projects you might want to automate file generation, like for example placeorder confirmation receipts, payment receipts, that can be based on a template you are using.

The library we will be using is Weasyprint. WeasyPrint is to combine multiple pieces of information into an HTML template and then converting it to a PDF document.

The supported version are Python 2.7, 3.3+

WeasyPrint has lot of dependencies, So this can be install it with pip.

pip install Weasyprint

Once you have installed WeasyPrint, you should have a weasyprint executable. This can be as simple:

weasyprint --version

This will Print WeasyPrint's version number you have installed.

weasyprint <Your_Website_URL> <Your_path_to_save_this_PDF>
Eg: weasyprint http://samplewebsite.com ./test.pdf

Here i have converted "http://samplewebsite.com" site to an test.pdf.

Let we write sample PDF Generation:

from weasyprint import HTML, CSS

    HTML('http://samplewebsite.com/').write_pdf('/localdirectory/test.pdf',

        stylesheets=[CSS(string='body { font-size: 10px }')])

This will also converts the page in to PDF, Here the change is we are writting custom stylesheet(CSS) for the body to change the font size using the "string" argument.

You can also pass the CSS File, This can be done using:

from django.conf import settings

    CSS(settings.STATIC_ROOT +  'css/main.css')

    Ex: HTML('http://samplewebsite.com/').write_pdf('/localdirectory/test.pdf',
        stylesheets=[CSS(settings.STATIC_ROOT +  'css/main.css')])

You can also pass multiple css files to this stylesheets array

Generating PDF Using Template:

Let we create a basic HTML file, that we will use as a template to generate PDF:

templates/home_page.html

        <html>
         <head>
             Home Page
         </head>
         <body>
          <h1>Hello !!!</h1>
          <p>First Pdf Generation using Weasyprint.</p>
         </body>
        </html>

Lets write a django function to render this template in a PDF:

from weasyprint import HTML, CSS
        from django.template.loader import get_template
        from django.http import HttpResponse

        def pdf_generation(request):
            html_template = get_template('templates/home_page.html')
            pdf_file = HTML(string=html_template).write_pdf()
            response = HttpResponse(pdf_file, content_type='application/pdf')
            response['Content-Disposition'] = 'filename="home_page.pdf"'
            return response

Here, we have used the get_template() function to fetch the HTML template file in the static root.

Finally, You can download your home_page.pdf