Dynamically generate a PDF to download from Workshop?

I want to generate a PDF on the fly, dynamically, on a user click. This PDF should be downloaded by the user once generated.
How can I write such function ?

You need to create a function that will generate this PDF and return it as base64 to Workshop.

Here is the example code

import base64
from weasyprint import HTML, CSS
from PyPDF2 import PdfReader, PdfWriter  # v3.0.0+
import io
from functions.api import function, String, OntologyEdit, Attachment
from ontology_sdk import FoundryClient
import pathlib
from .image import BASE_64_IMAGE
import font_roboto
from weasyprint.text.fonts import FontConfiguration
import fitz
import uuid
from ontology_sdk.ontology.objects import DummyAttachmentsAa
import tempfile
import os

# import io
# import base64
# from weasyprint import HTML, CSS
# from weasyprint.text.fonts import FontConfiguration
# import fitz  # PyMuPDF

def roboto_fontface_css():
    return """
    @import url('https://fonts.googleapis.com/css?family=Roboto');
    """

@function
def generatePDFasBase64() -> str:
    html_input = """
    <html>
        <head></head>
        <body>
            <h1>Hello, PDF!</h1>
            <p>This PDF was generated from scratch.</p>
        </body>
    </html>
    """

    uncompressed = False
    optimize_images = False
    font_config = FontConfiguration()
    font_css = roboto_fontface_css()
    body_css = "body { font-family: 'Roboto', sans-serif; }"
    full_css = font_css + body_css

    pdf_io = io.BytesIO()
    HTML(string=html_input).write_pdf(
        pdf_io,
        uncompressed_pdf=uncompressed,
        optimize_images=optimize_images,
        stylesheets=[CSS(string=full_css, font_config=font_config)],
        font_config=font_config,
        pdf_forms=True,
        pdf_version="1.4"
    )

    doc = fitz.open(stream=pdf_io.getvalue(), filetype="pdf")
    output_bytes = doc.tobytes(garbage=4, clean=True)
    doc.close()

    # Base64 encode
    return base64.b64encode(output_bytes).decode("ascii")

You can then configure a button in Workshop to export it.

Hi Vincent. I am running a similar code to create PDFs and last week it was working fine, but now I am getting PANGO font null error messages. Did you run into a similar issue.