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')
Answer from CyborgForever on Stack Overflow
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.

🌐
GitHub
github.com › xhtml2pdf › xhtml2pdf
GitHub - xhtml2pdf/xhtml2pdf: A library for converting HTML into PDFs using ReportLab · GitHub
A library for converting HTML into PDFs using ReportLab - xhtml2pdf/xhtml2pdf
Starred by 2.4K users
Forked by 655 users
Languages   Python 52.5% | HTML 45.2% | CSS 2.1%
Discussions

python - Generate PDF from HTML using Django and Reportlab - Stack Overflow
I want to generate a PDF from a webpage by clicking on a "Download PDF" button. I tried several modules including Reportlab and XHTML2PDF but I am not able to generate any pdf nor downloading it... Here is what I did with Reportlab, following Render HTML to PDF in Django site More on stackoverflow.com
🌐 stackoverflow.com
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
0
July 24, 2020
How to generate PDF file from an HTML file using Reportlab and Pisa in Python? - Stack Overflow
Pillow==2.3.0 PyPDF2==1.25.1 html5lib==0.999 oneconf==0.3.7.14.04.1 pdfkit==0.5.0 pisa==3.0.33 reportlab==3.0 · Seems like a broken installation issue... Does anyone know how to fix this or any alternative methods (approaches and / or different libraries) used to generate HTML files into PDFs? More on stackoverflow.com
🌐 stackoverflow.com
Reportlab, Weasy, Wkhtml - oh my! Which PDF/Printing plugin to use?
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? More on forum.djangoproject.com
🌐 forum.djangoproject.com
0
0
January 23, 2020
🌐
pdf noodle
pdfnoodle.com › home › blog › how to generate pdf using reportlab in python (updated 2025)
How to Generate PDF Using ReportLab in Python (Updated 2025) - pdf noodle
October 15, 2025 - ReportLab allows you to create PDFs from scratch using Python objects, giving developers precise control over layouts, fonts, tables, and vector graphics. This makes it ideal for applications that need custom report generation or dynamically ...
🌐
Reportlab
docs.reportlab.com › webintegration › Integrating_ReportLab_into_your_website
Web Integration - ReportLab Docs
RML is commercial software which is part of the ReportLab PLUS package. You will need to create a user account to download a trial version of ReportLab PLUS. This is a sample project which takes user input from an HTML form and generates a PDF containing what the user submitted.
🌐
Reportlab
docs.reportlab.com › clean_html
Cleaning HTML - ReportLab Docs
Remove all tags to output plain text. Example · >>> from rlextra.radxml.html_cleaner import cleanPlain >>> data = "<p>This is raw data with <em>HTML</em> <b>paragraph</b></p>" >>> cleanPlain(data) 'This is raw data with HTML paragraph' Here we detail rendering html in a PDF but also include the aforementioned cleanPlain
🌐
Medium
lprabodha1998.medium.com › how-to-convert-html-to-pdf-in-python-69474804fb8a
How to Convert HTML to PDF in Python? - Lahiru Prabodha
May 10, 2024 - import xhtml2pdf.pisa as pisa # Convert an HTML file to a PDF with open('input.html', 'rb') as f: pisa.CreatePDF(f, 'output.pdf') # Convert an HTML string to a PDF html = '<html><body>Hello World</body></html>' pisa.CreatePDF(html, 'output.pdf') ...
Find elsewhere
🌐
Medium
vonkunesnewton.medium.com › generating-pdfs-with-reportlab-ced3b04aedef
Generating pdfs with ReportLab - Ryan von Kunes Newton
April 6, 2018 - Let’s start to add some basic text to our pdf! Again, we’re going to use classes that already exist in platypus, Paragraph and PageBreak. A Paragraph takes two arguments, text and style. There’s not a whole lot of info on styles, so I’d suggest digging around with ipdb. However, there is a function that builds sample styles for us, getSampleStyleSheet which you can then modify. from reportlab.lib.styles import getSampleStyleSheetsample_style_sheet = getSampleStyleSheet()# if you want to see all the sample styles, this prints them sample_style_sheet.list()
🌐
Imaginary Landscape
imagescape.com › blog › python-solution-making-custom-pdfs-html
A Python Solution for Making Custom PDFs from HTML
February 7, 2017 - They also wanted the pdf to be ... for generating on-the-fly pdfs, and the xhtml2pdf library, which depends on Reportlab, offers a relatively easy way to convert an html web page to pdf while (more-or-less) preserving css styles....
🌐
Stack Overflow
stackoverflow.com › questions › 33883366 › how-to-generate-pdf-file-from-an-html-file-using-reportlab-and-pisa-in-python
How to generate PDF file from an HTML file using Reportlab and Pisa in Python? - Stack Overflow
import cStringIO import ho.pisa as pisa class FileUtil: @staticmethod def html_to_pdf(html, output_file): pdfFile = file(output_file, "wb") pdf = pisa.CreatePDF( cStringIO.StringIO(html.encode("ISO-8859-1")), pdfFile) pdfFile.close()
🌐
Reportlab
reportlab.com › docs › reportlab-userguide.pdf pdf
ReportLab PDF Library User Guide ReportLab Version 4.4.10
The ReportLab library forms the foundation of our commercial solution for PDF generation, Report Markup · Language (RML). This is available for evaluation on our web site with full documentation. We believe that · RML is the fastest and easiest way to develop rich PDF workflows. You work in a markup language at a sim- ilar level to HTML, using your favorite templating system to populate an RML document; then call our
🌐
Narkive
reportlab-users.reportlab.narkive.com › 1O2bPNv4 › problem-generating-pdf-from-django-python-html-template
[reportlab-users] Problem generating PDF from Django/Python HTML Template
So, you'll get a single line of text (probably raw HTML) starting at (0, 820) and trailing off the right edge of your PDF page into infinity - unless your intent is to generate one short string from the template. Our library does not convert HTML to PDF. You need to write the Python code to ...
🌐
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?
🌐
pythontutorials
pythontutorials.net › blog › how-to-convert-a-html-document-into-a-pdf-using-report-lab-with-python
How to Convert HTML Document to PDF Using ReportLab in Python: Step-by-Step Guide — pythontutorials.net
While ReportLab excels at building PDFs from scratch (using low-level drawing or high-level "flowable" elements like paragraphs and tables), it does not natively parse HTML. To bridge this gap, we’ll combine ReportLab with HTML parsing libraries like BeautifulSoup to extract content (text, headings, images, etc.) from HTML and render it into a polished PDF.
🌐
Reddit
reddit.com › r/python › looking for an "low dependency" or pythonesque way to generate pdf's
r/Python on Reddit: looking for an "low dependency" or pythonesque way to generate PDF's
October 10, 2022 -

I need to generate PDF's.

While pdfkit looks very promising with its ability to render HTML with styling (Which would absolutely be the most epicness as almost no new templating would have to be made) it also depends on wkhtmltopdf and maybe even a virtual X server.

I want my tool to be deployable without the hastle to install non pythonesque tools. I want people to be able to install my package and use it after installing its requirements.txt. previously I've been using FPDF but its also not so modern..

So anyone has any hints?

I'd also be open to hints about deployment if this is not as big of an issue as I think . As this is basically a webapp which people might run on their own PC's, I'm open to good firefox/chrome hints to print a styled page aswell.

🌐
API2PDF
api2pdf.com › home › blog › reportlab alternative for pdf generation in python
ReportLab Alternative for PDF generation in Python
October 21, 2024 - No installation required. Just “pip install api2pdf” and grab your API key and you are ready to go. Since Api2Pdf is an API to convert HTML to PDF, all processing takes place on Api2Pdf’s servers.
🌐
Pythonrepo
pythonrepo.com › repo › xhtml2pdf-xhtml2pdf-python-working-with-html-and-xml
A library for converting HTML into PDFs using ReportLab | PythonRepo
February 19, 2022 - xhtml2pdf is a HTML to PDF converter using Python, the ReportLab Toolkit, html5lib and PyPDF2. It supports HTML5 and CSS 2.1 (and some of CSS 3).