Examples

1. Generating QR Codes

PlutoPrint has a built-in CSS function -pluto-qrcode() that generates QR codes dynamically within the CSS content property.

import plutoprint

HTML = """
<div class="card">
  <h3>Contact Me</h3>
  <div class="qr-code"></div>
</div>
"""

STYLE = """
.card {
    border: 1px solid #ccc;
    padding: 20px;
    width: 200px;
    text-align: center;
    font-family: sans-serif;
}
.qr-code::before {
    /* Syntax: -pluto-qrcode('CONTENT', COLOR) */
    content: -pluto-qrcode('https://github.com/plutoprint', #f59e0b);
    display: block;
    width: 150px;
    height: 150px;
    margin: 0 auto;
}
"""

book = plutoprint.Book()
book.load_html(HTML, user_style=STYLE)
book.write_to_png("qrcode_card.png")

2. Custom Charts with Matplotlib

You can hook into the resource loading process to generate images in Python memory (like Matplotlib charts) and serve them to the HTML renderer without saving files to disk.

import plutoprint
import matplotlib.pyplot as plt
import urllib.parse
import io

class ChartFetcher(plutoprint.ResourceFetcher):
    def fetch_url(self, url):
        # We intercept URLs starting with 'chart:'
        if not url.startswith('chart:'):
            return super().fetch_url(url)

        # Parse data from URL string
        # e.g., chart:10,20,30
        values = [float(v) for v in urllib.parse.unquote(url[6:]).split(',')]

        # Generate Chart
        plt.figure(figsize=(4, 3))
        plt.bar(range(len(values)), values)
        plt.title('Generated Chart')

        # Save to memory buffer as SVG
        buffer = io.BytesIO()
        plt.savefig(buffer, format='svg')
        plt.close()

        # Return as a PlutoPrint Resource
        return plutoprint.ResourceData(
            buffer.getvalue(), 
            "image/svg+xml", 
            "utf-8"
        )

# Attach the custom fetcher
book = plutoprint.Book()
book.custom_resource_fetcher = ChartFetcher()

# The HTML requests the magic URL
html = "<img src='chart:10,50,30,40,90'>"
book.load_html(html)
book.write_to_png("chart_output.png")