Generate PDF from HTML in django using weasyprint

Reading Time : ~ .

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

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Integrating Gitlab in django project with gitlab api for gitlab authentication and access Nikhila Mergu

This is a simple way to integrate gitlab authentication in your django apps.

We can get user verified email id, general information, git lab URL ...

Continue Reading...
Best Practices of Using Django Celery in Django Social Auth Sandeep Jagata

Best Practices of Using Django Celery in Django Social Auth.

Continue Reading...
Preserve file names with sorl for better SEO Ashwin Kumar

We use sorl-thumbnail for scaling images by keeping the original one intact. Sorl proven to be great tool for generating different sized images throughout website. ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties