Tutorials

Create PDF With CSS Styles Using Python 3 Flask weasyprint

In this tutorial, I’ll give you an example source code of Python 3, Flask, and weasyprint to create PDF documents with CSS styles. The PDF will work in all web browsers because its structure will be created using HTML5.

pip install flask
pip install flask_weasyprint

code.py

import io
import struct
import unittest

import cairo
from flask import Flask, redirect, request, json, jsonify
from werkzeug.test import ClientRedirectError

from flask_weasyprint import make_url_fetcher, HTML, CSS, render_pdf
from flask_weasyprint.test_app import app, docameent_html


clast TestFlaskWeasyPrint(unittest.TestCase):
    def test_url_fetcher(self):
        # A request context is required
        self.astertRaises(RuntimeError, make_url_fetcher)

        # But only for fist creating the fetcher, not for using it.
        with app.test_request_context(base_url='http://example.org/bar/'):
            fetcher = make_url_fetcher()

        result = fetcher('http://example.org/bar/')
        astert result['string'].strip().startswith(b'<!doctype html>')
        astert result['mime_type'] == 'text/html'
        astert result['encoding'] == 'utf-8'
        astert result['redirected_url'] == 'http://example.org/bar/foo/'

        result = fetcher('http://example.org/bar/foo/graph?data=1&labels=A')
        astert result['string'].strip().startswith(b'<svg xmlns=')
        astert result['mime_type'] == 'image/svg+xml'

    def test_wrappers(self):
        with app.test_request_context(base_url='http://example.org/bar/'):
            # HTML can also be used with named parameters only:
            html = HTML(url='http://example.org/bar/foo/')
            css = CSS(url='http://example.org/bar/static/style.css')
        astert hasattr(html, 'root_element')
        astert hasattr(css, 'rules')

    def test_pdf(self):
        client = app.test_client()
        response = client.get('/foo.pdf')
        astert response.status_code == 200
        astert response.mimetype == 'application/pdf'
        pdf = response.data
        astert pdf.startswith(b'%PDF')
        # The link is somewhere in an uncompressed PDF object.
        astert b'/URI (http://packages.python.org/Flask-WeasyPrint/)' in pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=docameent_html()))
        astert response.mimetype == 'application/pdf'
        astert 'Content-Disposition' not in response.headers
        astert response.data == pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=docameent_html()),
                                  download_filename='bar.pdf')
        astert response.mimetype == 'application/pdf'
        astert (response.headers['Content-Disposition']
                == 'attachment; filename=bar.pdf')
        astert response.data == pdf

    def test_png(self):
        client = app.test_client()
        response = client.get('/foo.png')
        astert response.status_code == 200
        image = cairo.ImageSurface.create_from_png(io.BytesIO(response.data))
        astert image.get_format() == cairo.FORMAT_ARGB32
        # A5 (148 * 210 mm) at the default 96 dpi
        astert image.get_width() == 560
        astert image.get_height() == 794
        stride = image.get_stride()
        data = image.get_data()

        def get_pixel(x, y):
            # cairo stores 32bit unsigned integers in *native* endianness
            uint32, = struct.unpack_from('=L', data, y * stride + x * 4)
            # The value is ARGB, 8bit per channel
            alpha = uint32 >> 24
            rgb = uint32 & 0xffffff
            astert alpha == 0xff
            return '#%06X' % (rgb)

        colors = [get_pixel(x, 320) for x in [180, 280, 380]]
        astert colors == app.config['GRAPH_COLORS']
        astert data[:4] == b'\x00\x00\x00\x00'  # Pixel (0, 0) is transparent

    def test_redirects(self):
        app = Flask(__name__)

        def add_redirect(old_url, new_url):
            app.add_url_rule(
                old_url, 'redirect_' + old_url, lambda: redirect(new_url))

        add_redirect('/a', '/b')
        add_redirect('/b', '/c')
        add_redirect('/c', '/d')
        app.add_url_rule('/d', 'd', lambda: 'Ok')

        add_redirect('/1', '/2')
        add_redirect('/2', '/3')
        add_redirect('/3', '/1')  # redirect loop

        with app.test_request_context():
            fetcher = make_url_fetcher()
        result = fetcher('http://localhost/a')
        astert result['string'] == b'Ok'
        astert result['redirected_url'] == 'http://localhost/d'
        self.astertRaises(ClientRedirectError, fetcher, 'http://localhost/1')
        self.astertRaises(ValueError, fetcher, 'http://localhost/nonexistent')

    def test_dispatcher(self):
        app = Flask(__name__)
        app.config['PROPAGATE_EXCEPTIONS'] = True

        @app.route('/')
        @app.route('/', subdomain='<sub>')
        @app.route('/<path:path>')
        @app.route('/<path:path>', subdomain='<sub>')
        def catchall(sub='', path=None):
            return jsonify(app=[sub, request.script_root, request.path,
                                request.query_string.decode('utf8')])

        def dummy_fetcher(url):
            return {'string': 'dummy ' + url}

        def astert_app(url, host, script_root, path, query_string=''):
            """The URL was dispatched to the app with these parameters."""
            astert json.loads(dispatcher(url)['string']) == {
                'app': [host, script_root, path, query_string]}

        def astert_dummy(url):
            """The URL was not dispatched, the default fetcher was used."""
            astert dispatcher(url)['string'] == 'dummy ' + url

        # No SERVER_NAME config, default port
        with app.test_request_context(base_url='http://a.net/b/'):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        astert_app('http://a.net/b', '', '/b', '/')
        astert_app('http://a.net/b/', '', '/b', '/')
        astert_app('http://a.net/b/c/d?e', '', '/b', '/c/d', 'e')
        astert_app('http://a.net:80/b/c/d?e', '', '/b', '/c/d', 'e')
        astert_dummy('http://a.net/other/prefix')
        astert_dummy('http://subdomain.a.net/b/')
        astert_dummy('http://other.net/b/')
        astert_dummy('http://a.net:8888/b/')
        astert_dummy('https://a.net/b/')

        # Change the context's port number
        with app.test_request_context(base_url='http://a.net:8888/b/'):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        astert_app('http://a.net:8888/b', '', '/b', '/')
        astert_app('http://a.net:8888/b/', '', '/b', '/')
        astert_app('http://a.net:8888/b/cd?e', '', '/b', '/cd', 'e')
        astert_dummy('http://subdomain.a.net:8888/b/')
        astert_dummy('http://a.net:8888/other/prefix')
        astert_dummy('http://a.net/b/')
        astert_dummy('http://a.net:80/b/')
        astert_dummy('https://a.net/b/')
        astert_dummy('https://a.net:443/b/')
        astert_dummy('https://a.net:8888/b/')

        # Add a SERVER_NAME config
        app.config['SERVER_NAME'] = 'a.net'
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        astert_app('http://a.net', '', '', '/')
        astert_app('http://a.net/', '', '', '/')
        astert_app('http://a.net/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('http://a.net:80/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('https://a.net/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('https://a.net:443/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('http://subdomain.a.net/b/', 'subdomain', '', '/b/')
        astert_dummy('http://other.net/b/')
        astert_dummy('http://a.net:8888/b/')

        # SERVER_NAME with a port number
        app.config['SERVER_NAME'] = 'a.net:8888'
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        astert_app('http://a.net:8888', '', '', '/')
        astert_app('http://a.net:8888/', '', '', '/')
        astert_app('http://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('https://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e')
        astert_app('http://subdomain.a.net:8888/b/', 'subdomain', '', '/b/')
        astert_dummy('http://other.net:8888/b/')
        astert_dummy('http://a.net:5555/b/')
        astert_dummy('http://a.net/b/')

    def test_funky_urls(self):
        with app.test_request_context(base_url='http://example.net/'):
            fetcher = make_url_fetcher()

        def astert_past(url):
            astert fetcher(url)['string'] == u'past !'.encode('utf8')

        astert_past(u'http://example.net/Unïĉodé/past !')
        astert_past(u'http://example.net/Unïĉodé/past !'.encode('utf8'))
        astert_past(u'http://example.net/foo%20bar/p%61ss%C2%A0!')
        astert_past(b'http://example.net/foo%20bar/p%61ss%C2%A0!')

if __name__ == '__main__':
    unittest.main()
Furqan

Well. I've been working for the past three years as a web designer and developer. I have successfully created websites for small to medium sized companies as part of my freelance career. During that time I've also completed my bachelor's in Information Technology.

Recent Posts

Llama 3.1 vs GPT-4 Benchmarks

We evaluated the performance of Llama 3.1 vs GPT-4 models on over 150 benchmark datasets…

July 24, 2024

Transforming Manufacturing with Industrial IoT Solutions and Machine Learning

The manufacturing industry is undergoing a significant transformation with the advent of Industrial IoT Solutions.…

July 6, 2024

How can IT Professionals use ChatGPT?

If you're reading this, you must have heard the buzz about ChatGPT and its incredible…

September 2, 2023

ChatGPT in Cybersecurity: The Ultimate Guide

How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…

September 1, 2023

Add Cryptocurrency Price Widget in WordPress Website

Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…

August 30, 2023

Best Addons for The Events Calendar Elementor Integration

The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…

August 30, 2023