Custom Resource Fetchers

By default, PlutoPrint fetches resources (images, stylesheets, fonts) using standard file system paths or HTTP/HTTPS requests. However, you might need to load resources from:

  1. A database.
  2. Compressed archives.
  3. In-memory generation (like the Matplotlib example).
  4. Authenticated endpoints requiring custom headers.

To achieve this, you can extend the ResourceFetcher class.

Implementation

import plutoprint

class MyFetcher(plutoprint.ResourceFetcher):
    def fetch_url(self, url: str) -> plutoprint.ResourceData:
        print(f"Fetching: {url}")

        if url == "myprotocol://logo.png":
            # Return hardcoded binary data
            with open("local_logo.png", "rb") as f:
                data = f.read()
            return plutoprint.ResourceData(data, "image/png")

        # Fallback to default behavior for everything else
        return super().fetch_url(url)

Registering the Fetcher

Once instantiated, you must attach your fetcher to the Book instance:

book = plutoprint.Book()
book.custom_resource_fetcher = MyFetcher()