UPDATE for 2021:

Since this answer is over half a decade old, some new solutions have become available. These days, I tend to use WeasyPrint, which has the additional benefit of being BSD licensed instead of LGPL. It is a tad slower, however.

https://weasyprint.org/


ORIGINAL ANSWER:

I'd recommend using wkhtmltopdf.

The short answer? On Ubuntu, install a binary:

apt-get install wkhtmltopdf

On CentOS / RedHat:

yum install wkhtmltox-0.12.2.1_linux-centos6-amd64.rpm

Then pip install a Python package:

pip install pdfkit

Then the code:

import pdfkit
 
input_filename = 'README.html'
output_filename = 'README.pdf'
 
with open(input_filename, 'r') as f:
    html_text = f.read()
 
pdfkit.from_string(html_text, output_filename)

For the long answer and details, I put together a blog post:

https://www.pyphilly.org/generating-pdf-markdown-or-html/

That should take care of the PDF creation; you'll have to decide how you want to handle the download. Good luck!

Answer from FlipperPA on Stack Overflow
🌐
Simple is Better Than Complex
simpleisbetterthancomplex.com › tutorial › 2016 › 08 › 08 › how-to-export-to-pdf.html
How to Export to PDF
August 8, 2016 - A good thing about WeasyPrint is that you can convert a HTML document to a PDF. So you can create a regular Django template, print and format all the contents and then pass it to the WeasyPrint library to do the job of creating the pdf.
Discussions

python - Django Reportlab using HTML - Stack Overflow
Hello guys I'm trying to make a little PDF with python django using the reportlab library I've made some pdf with just some text but I have no idea how to do it with html, I wonder if you guys can ... More on stackoverflow.com
🌐 stackoverflow.com
July 14, 2016
How to convert a html document into a pdf using report lab with python - Stack Overflow
I am trying to convert a html document that I have created into a pdf using report lab. The html document is below. I am unsure on how to do this and I have looked online and cant seem to find a so... More on stackoverflow.com
🌐 stackoverflow.com
July 21, 2017
How to create a pdf report Reportlab
0 I was wondering how could I create a pdf report using reportlab. I’m developing a web site and I’m using Django. In my project I charged a lot of icons, and I was using a Javascript function(PrintThisjs), but it doesn’t work well. Seems like Reportlab is a good solution. Thanks 🙂 More on forum.djangoproject.com
🌐 forum.djangoproject.com
11
1
July 24, 2020
python - Printing to PDF Django & ReportLab - Stack Overflow
My Question, does anyone have an ... on the html I have a print button which currently runs my print to pdf script. ... OK, so of course I'm a newbie and learning but here' what I did, I essentially passed a record number through a url into my function. I'm sure there's a better (more secure) way, but I secured it with a superuser decorator for now. (from here: django @login_required ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @saijalshakya › generating-pdf-with-reportlab-in-django-ee0235c2f133
Generating PDF with reportLab in Django | by Saijal Shakya | Medium | Medium
April 27, 2019 - To download libraries for python you can checkout PyPi. PyPi is one of the best repository of software for Python. ... from io import BytesIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsefrom reportlab.lib.pagesizes import letter, landscapefrom reportlab.lib.pagesizes import A4
🌐
Django
django.readthedocs.io › en › 2.0.x › howto › outputting-pdf.html
Outputting PDFs with Django — Django 2.0.14.dev20190701080343 documentation
You can install ReportLab with pip: ... If that command doesn’t raise any errors, the installation worked. The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects, and Django’s HttpResponse objects are file-like objects.
🌐
Stack Overflow
stackoverflow.com › questions › 38385591 › django-reportlab-using-html
python - Django Reportlab using HTML - Stack Overflow
July 14, 2016 - Not directly answering your question, but you can create PDF via HTML, https://pypi.python.org/pypi/django-wkhtmltopdf ... Sign up to request clarification or add additional context in comments.
Top answer
1 of 2
8

As you already know how to use ReportLab, I guess that this would do the job : https://github.com/xhtml2pdf/xhtml2pdf

xhtml2pdf

A library for converting HTML into PDFs using ReportLab

Sample code, taken from the Github :

# -*- coding: utf-8 -*-
# Copyright 2010 Dirk Holtwick, holtwick.it
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "$Revision: 194 $"
__author__  = "$Author: holtwick $"
__date__    = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $"

import os
import sys
import cgi
import cStringIO
import logging

import xhtml2pdf.pisa as pisa

# Shortcut for dumping all logs to the screen
pisa.showLogging()

def dumpErrors(pdf, showLog=True):
    #if showLog and pdf.log:
    #    for mode, line, msg, code in pdf.log:
    #        print "%s in line %d: %s" % (mode, line, msg)
    #if pdf.warn:
    #    print "*** %d WARNINGS OCCURED" % pdf.warn
    if pdf.err:
        print "*** %d ERRORS OCCURED" % pdf.err

def testSimple(
    data="""Hello <b>World</b><br/><img src="img/test.jpg"/>""",
    dest="test.pdf"):

"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""

    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        file(dest, "wb")
        )

    if pdf.err:
        dumpErrors(pdf)
    else:
        pisa.startViewer(dest)

def testCGI(data="Hello <b>World</b>"):

    """
    This one shows, how to get the resulting PDF as a
    file object and then send it to STDOUT
    """

    result = cStringIO.StringIO()

    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        result
        )

    if pdf.err:
        print "Content-Type: text/plain"
        print
        dumpErrors(pdf)
    else:
        print "Content-Type: application/octet-stream"
        print
        sys.stdout.write(result.getvalue())

def testBackgroundAndImage(
    src="test-background.html",
    dest="test-background.pdf"):

    """
    Simple test showing how to create a PDF file from
    PML Source String. Also shows errors and tries to start
    the resulting PDF
    """

    pdf = pisa.CreatePDF(
        file(src, "r"),
        file(dest, "wb"),
        log_warn = 1,
        log_err = 1,
        path = os.path.join(os.getcwd(), src)
        )

    dumpErrors(pdf)
    if not pdf.err:
        pisa.startViewer(dest)

def testURL(
    url="http://www.htmltopdf.org",
    dest="test-website.pdf"):

    """
    Loading from an URL. We open a file like object for the URL by
    using 'urllib'. If there have to be loaded more data from the web,
    the pisaLinkLoader helper is passed as 'link_callback'. The
    pisaLinkLoader creates temporary files for everything it loads, because
    the Reportlab Toolkit needs real filenames for images and stuff. Then
    we also pass the url as 'path' for relative path calculations.
    """
    import urllib

    pdf = pisa.CreatePDF(
        urllib.urlopen(url),
        file(dest, "wb"),
        log_warn = 1,
        log_err = 1,
        path = url,
        link_callback = pisa.pisaLinkLoader(url).getFileName
        )

    dumpErrors(pdf)
    if not pdf.err:
        pisa.startViewer(dest)

if __name__=="__main__":

    testSimple()
    # testCGI()
    #testBackgroundAndImage()
    #testURL()

Or you can use pdfkit :

https://pypi.python.org/pypi/pdfkit

Before using it you need to install some things :

pip install pdfkit
sudo apt-get install wkhtmltopdf

Sample code to generate pdf :

import pdfkit

pdfkit.from_url('http://stackoverflow.com', 'out.pdf')
pdfkit.from_file('test.html', 'out2.pdf')
pdfkit.from_string('Thanks for reading!', 'out3.pdf')
2 of 2
8

If you use django framework you could use django-easy-pdf. I think it's the least painfull way to generate PDF from Html. Here's the template and views of my project:

#Import the easy_pdf rendering
from easy_pdf.rendering import render_to_pdf_response

#Here's the detail view function
def detail_to_pdf(request,id):
    template = 'renderdetail.html'
    kucing = Kucing.objects.get(id = id)
    context = {'kucing' : kucing}
    return render_to_pdf_response(request,template,context)

The Template is:

{% extends "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>PROFILE : {{ kucing.nama }}- ID:{{ kucing.id }}</h1>
            <img src="/media/{{ kucing.foto }}"><br>
            <p>Nama : {{ kucing.nama }}</p><br>
            <p>Hp : {{ kucing.hp}}</p><br>
            <p>Poin : {{ kucing.poin }}</p><br>
            <a href="{% url 'kucing_makan' kucing.id %}">Makan</a>
            <a href="{% url 'kucing_berburu' kucing.id %}">Berburu</a>
            <hr>
            <h5><a href="{% url 'kucing_home' %}">Back To Home</a></h5>|
            <h5><a href="{% url 'kucing_list' %}">See Another Kucing</a></h5>
        </div>
    </div>
{% endblock %}

You also able to use Class Based Views by overriding PDFTemplateViews. You can see more on the Docs.

Find elsewhere
🌐
Django Forum
forum.djangoproject.com › using django › forms & apis
How to create a pdf report Reportlab - Forms & APIs - Django Forum
July 24, 2020 - 0 I was wondering how could I create a pdf report using reportlab. I’m developing a web site and I’m using Django. In my project I charged a lot of icons, and I was using a Javascript function(PrintThisjs), but it doesn’t work well. Seems like Reportlab is a good solution. Thanks 🙂
🌐
Django Documentation
docs.djangoproject.com › en › 5.0 › howto › outputting-pdf
How to create PDF files | Django documentation | Django
You can install ReportLab with pip: ... If that command doesn’t raise any errors, the installation worked. The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects, and Django’s FileResponse objects accept file-like objects.
🌐
Django
django.readthedocs.io › en › 1.5.x › howto › outputting-pdf.html
Outputting PDFs with Django — Django 1.5.12 documentation
April 12, 2017 - The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects, and Django’s HttpResponse objects are file-like objects.
🌐
Django
django.readthedocs.io › en › 1.9.x › howto › outputting-pdf.html
Outputting PDFs with Django — Django 1.9.14.dev20170906233242 documentation
September 6, 2017 - It ships with an example of how to integrate it with Django. HTMLdoc is a command-line script that can convert HTML to PDF. It doesn’t have a Python interface, but you can escape out to the shell using system or popen and retrieve the output in Python. Notice that there isn’t a lot in these examples that’s PDF-specific – just the bits using reportlab...
🌐
LinkedIn
linkedin.com › pulse › generating-pdfs-through-django-supriyo-ghosh
Generating PDF’s Through Django
January 3, 2018 - Generating PDF’s Django is able to output PDF files dynamically using views. This is made possible by the excellent, open-source ReportLab Python PDF library.
🌐
Stack Overflow
stackoverflow.com › questions › 58150122 › printing-to-pdf-django-reportlab
python - Printing to PDF Django & ReportLab - Stack Overflow
My Question, does anyone have an idea of how I might render to pdf AND print to PDF, i.e. next to the record on the html I have a print button which currently runs my print to pdf script. ... OK, so of course I'm a newbie and learning but here' what I did, I essentially passed a record number through a url into my function. I'm sure there's a better (more secure) way, but I secured it with a superuser decorator for now. (from here: django @login_required decorator for a superuser)
🌐
Spapas
spapas.github.io › 2015 › 11 › 27 › pdf-in-django
PDFs in Django: The essential guide — /var/
xhtml2pdf (formerly named pisa) is an open source library that can convert HTML/CSS pages to PDF using ReportLab. django-xhtml2pdf is a wrapper around xhtml2pdf that makes integration with Django easier.
🌐
ASSIST Software Romania
assist-software.net › blog › how-create-pdf-files-python-django-application-using-reportlab
How to create PDF files in a Python/Django application using ReportLab | ASSIST Software
In order to be as modular as possible we’ve created a class named PdfPrint that contains several methods for creating different elements. This class has an __init__ method with two parameters: buffer and pagesize. Buffer is used to hold data and pagesize is used to set page type and it's width and height. ReportLab has a series of build-in types: A0 to A6, B0 to B6 and letter type, A4 being the default format if we don't give one.
🌐
Django
docs.djangoproject.com › en › 3.2 › howto › outputting-pdf
Outputting PDFs with Django | Django documentation | Django
April 13, 2020 - You can install ReportLab with pip: ... If that command doesn’t raise any errors, the installation worked. The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects, and Django’s FileResponse objects accept file-like objects.
🌐
Reportlab
docs.reportlab.com › webintegration › Integrating_ReportLab_into_your_website
Web Integration - ReportLab Docs
This is a simple demonstration ... name - and convert the output into a PDF which is returned to the browser. This project simply reads the template file 'hello.rml' into memory, and then substitutes a particular string using the Django templating engine....
🌐
Django
django.readthedocs.io › en › 1.6.x › howto › outputting-pdf.html
Outputting PDFs with Django — Django 1.6.12.dev20160216120443 documentation
October 3, 2017 - The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects, and Django’s HttpResponse objects are file-like objects.
🌐
Django Forum
forum.djangoproject.com › using django › getting started
Reportlab, Weasy, Wkhtml - oh my! Which PDF/Printing plugin to use? - Getting Started - Django Forum
January 23, 2020 - I am seeking to have a template of mine able to be printed with sensible defaults. I need to print a table, some images and a footer. The Django Docs suggest Reportlab - but it seems that the Reportlab docs are not Django specific. django-wkhtmltopdf seems pretty easy - but can it handle footers ok?