At work to deal with PDF generation I've been looking into WeasyPrint. It has a nice Flask utility that lets you render from routes
from flask import Flask, render_template, url_for
from flask_weasyprint import render_pdf
app = Flask(__name__)
@app.route("/hello/<name>")
def hello_html(name):
return render_template("hello.html", name=name)
@app.route("/hello/<name>.pdf")
def hello_pdf(name):
return render_pdf(url_for("hello_html", name=name))
Internally render_pdf constructs a werkzeug.test.Client to "simulate sending requests to a WSGI application without running a WSGI or HTTP server" to 1. fetch the rendered "hello.html" template and 2. fetch a static asset stylesheet. (https://github.com/Kozea/Flask-WeasyPrint/blob/main/flask_weasyprint/__init__.py#L101-L116)
I'm not too familiar with the Litestar internals to know where to start looking for any similar mechanism to werkzeug.test.Client.
Any advice?
For some context I'll add that I've tried going the regular HTTP way:
- serving a static asset through Litestar:
/static/foo.png(I can navigate to this fine) - a route for HTML:
/report.html - a route for PDF:
/report.pdfusingweasyprint.HTMLwhich can fetch external assets and can be given a base URL
I just render the template via Jinja to get this output
<img src="/static/foo.png">
<p>Hello world</p>
This serves just fine from <base>/report.html, but from <base>/report.pdf I call weasyprint.HTML(string=<rendered_html>, base_url=<base>) which fails to fetch the image ("weasyprint - images - Failed to load image at 'http://<base>/static/foo.png': TimeoutError: timed out").