Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: render web elements in PDF export (#8458)

Péter Gyarmati9032cbba414c
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.md
index a8f47a89ea..42c483d9cf 100644
--- a/docs/guides/exporting.md
+++ b/docs/guides/exporting.md
@@ -134,11 +134,60 @@ enables exporting to PDF and other formats with Pandoc. See this [publishing](./
You can export directly with marimo:
```bash
+# Hide code cells in the exported PDF
marimo export pdf notebook.py -o notebook.pdf --no-include-inputs
+
+# Disable rasterized output capture
+marimo export pdf notebook.py -o notebook.pdf --no-include-inputs --no-rasterize-outputs
+
+# Use a live server for raster capture
+marimo export pdf notebook.py -o notebook.pdf --no-include-inputs --raster-server=live
```
The `--no-include-inputs` flag hides Python code cells while keeping markdown and cell outputs in the generated PDF.
+Rasterized PNG fallback capture for marimo widget HTML (including anywidgets) and Vega outputs is enabled by default before `nbconvert` PDF conversion. Use `--no-rasterize-outputs` to disable it. Rasterization works with both `--webpdf` and `--no-webpdf`.
+
+Rasterization runs only when outputs are included (the default `--include-outputs` mode). Use `--raster-scale` (range `1.0` to `4.0`, default `4.0`) to trade export speed/file size for sharper captured output. Use `--raster-server=static` (default) for a static capture page, or `--raster-server=live` to capture through a live notebook server.
+
+!!! warning "Choose the raster server mode carefully"
+
+ marimo gives you control over how output is captured.
+ Use `--raster-server=live` when a widget needs Python to finish rendering.
+ Otherwise, prefer the default `--raster-server=static`.
+
+The notebook below is a concrete case where `--raster-server=live` helps.
+
+/// marimo-embed-file
+ size: xlarge
+ mode: edit
+ filepath: examples/outputs/live_raster.py
+///
+
+This widget starts at `Initializing...` and then updates to
+`count is ... from ... host` after it receives data from Python.
+Static capture can freeze the initial placeholder; live capture gets the
+updated output.
+
+```bash
+# Static mode captures only the initial "Initializing..." placeholder
+marimo export pdf examples/outputs/live_raster.py \
+ -o live-raster-static.pdf --raster-server=static --no-sandbox --no-include-inputs
+
+# Live mode captures the updated widget output
+marimo export pdf examples/outputs/live_raster.py \
+ -o live-raster-live.pdf --raster-server=live --no-sandbox --no-include-inputs
+```
+
+!!! note "Rasterization dependencies"
+
+ Rasterized output capture requires Playwright and Chromium:
+
+ ```bash
+ uv pip install playwright
+ playwright install chromium
+ ```
+
If you export to a Jupyter notebook, you can leverage various Jupyter ecosystem tools. For PDFs, you will
need to have [Pandoc](https://nbconvert.readthedocs.io/en/latest/install.html#installing-pandoc) and [TeX](https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex) installed. The examples below use `uvx`, which you can obtain by [installing `uv`](https://docs.astral.sh/uv/getting-started/installation/).
diff --git a/examples/outputs/live_raster.py b/examples/outputs/live_raster.py
new file mode 100644
index 0000000000..29e7f3be85
--- /dev/null
+++ b/examples/outputs/live_raster.py
@@ -0,0 +1,95 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "anywidget==0.9.21",
+# "marimo>=0.20.2",
+# "traitlets==5.14.3",
+# ]
+# ///
+import marimo
+
+__generated_with = "unknown"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(CounterWidget):
+ CounterWidget(count=42)
+ return
+
+
+def _(anywidget, os, traitlets):
+ class CounterWidget(anywidget.AnyWidget):
+ _esm = """
+ export default async () => {
+ let hostName = null;
+
+ return {
+ initialize({ model }) {
+ // This message gets handled by _handle_custom_msg on the Python side
+ model.send({ event: "requestHostName" });
+ },
+
+ render({ model, el }) {
+ let count = () => model.get("count");
+ let btn = document.createElement("button");
+ btn.classList.add("counter-button");
+ btn.innerHTML = `Initializing...`;
+
+ // Set proper HTML content once message arrives from Python connection
+ model.on("msg:custom", (msg, buffers) => {
+ hostName = msg.response;
+ btn.innerHTML = `count is ${count()} from ${hostName} host`;
+ });
+
+ btn.addEventListener("click", () => {
+ model.set("count", count() + 1);
+ model.save_changes();
+ });
+
+ model.on("change:count", () => {
+ btn.innerHTML =
+ hostName
+ ? `count is ${count()} from ${hostName} host`
+ : `Initializing...`;
+ });
+
+ el.appendChild(btn);
+ },
+ };
+ };
+ """
+ _css = """
+ .counter-button {
+ background: #387262;
+ border: 0;
+ border-radius: 10px;
+ padding: 10px 50px;
+ color: white;
+ }
+ """
+ count = traitlets.Int(0).tag(sync=True)
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.on_msg(self._handle_custom_msg)
+
+ def _handle_custom_msg(self, *args, **kwargs):
+ self.send({"response": os.name})
+
+ return (CounterWidget,)
+
+
[email protected](hide_code=True)
+def _():
+ import marimo as mo
+ import anywidget
+ import traitlets
+ import os
+
+ return anywidget, os, traitlets
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 49e41693ff..cef25328c1 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -549,6 +549,30 @@ Requires nbformat and nbconvert to be installed.
"try standard PDF export (pandoc + TeX) first and fall back to WebPDF."
),
)
+ "--rasterize-outputs/--no-rasterize-outputs",
+ default=True,
+ type=bool,
+ help=(
+ "Rasterize marimo widget HTML and Vega outputs to PNG fallbacks before PDF "
+ "conversion (enabled by default)."
+ ),
+)
+ "--raster-scale",
+ type=click.FloatRange(min=1.0, max=4.0),
+ default=4.0,
+ help="Scale factor for rasterized output screenshots.",
+)
+ "--raster-server",
+ type=click.Choice(["static", "live"], case_sensitive=False),
+ default="static",
+ help=(
+ "Server mode used for raster capture. Use 'static' (default) for "
+ "faster captures, or 'live' if outputs require a live Python connection."
+ ),
+)
@click.option(
"--watch/--no-watch",
default=False,
@@ -582,13 +606,18 @@ Requires nbformat and nbconvert to be installed.
type=click.Path(exists=True, file_okay=True, dir_okay=False),
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def pdf(
+ ctx: click.Context,
name: str,
output: Path,
watch: bool,
include_outputs: bool,
include_inputs: bool,
webpdf: bool,
+ rasterize_outputs: bool,
+ raster_scale: float,
+ raster_server: str,
sandbox: Optional[bool],
force: bool,
args: tuple[str],
@@ -596,6 +625,19 @@ def pdf(
"""Run a notebook and export it as a PDF file."""
import sys
+ if not include_outputs:
+ rasterize_source = ctx.get_parameter_source("rasterize_outputs")
+ raster_scale_source = ctx.get_parameter_source("raster_scale")
+ raster_server_source = ctx.get_parameter_source("raster_server")
+ if (
+ rasterize_source is not click.core.ParameterSource.DEFAULT
+ or raster_scale_source is not click.core.ParameterSource.DEFAULT
+ or raster_server_source is not click.core.ParameterSource.DEFAULT
+ ):
+ raise click.ClickException(
+ "Rasterization options require --include-outputs."
+ )
+
if include_outputs:
# Set default, if not provided
if sandbox is None:
@@ -635,6 +677,28 @@ def pdf(
) from None
cli_args = parse_args(args) if include_outputs else {}
+ rasterization_enabled = include_outputs and rasterize_outputs
+ if rasterization_enabled:
+ try:
+ DependencyManager.playwright.require(
+ "for rasterized PDF output export"
+ )
+ except ModuleNotFoundError as e:
+ if getattr(e, "name", None) == "playwright":
+ raise MarimoCLIMissingDependencyError(
+ "Playwright is required to rasterize HTML outputs for PDF export.",
+ "playwright",
+ followup_commands=get_playwright_chromium_setup_commands(),
+ ) from None
+ raise
+
+ from marimo._server.export._pdf_raster import PDFRasterizationOptions
+
+ rasterization_options = PDFRasterizationOptions(
+ enabled=rasterization_enabled,
+ scale=raster_scale,
+ server_mode=raster_server,
+ )
def export_callback(
file_path: MarimoPath,
@@ -648,6 +712,7 @@ def pdf(
webpdf=webpdf,
cli_args=cli_args,
argv=list(args) if include_outputs else None,
+ rasterization_options=rasterization_options,
)
)
except ModuleNotFoundError as e:
diff --git a/marimo/_cli/export/thumbnail.py b/marimo/_cli/export/thumbnail.py
index 22a2148eb7..693e2c2bb0 100644
--- a/marimo/_cli/export/thumbnail.py
+++ b/marimo/_cli/export/thumbnail.py
@@ -6,10 +6,6 @@ import json
import os
import subprocess
import sys
-import threading
-from contextlib import AbstractContextManager
-from functools import partial
-from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
@@ -21,6 +17,7 @@ from marimo._cli.parse_args import parse_args
from marimo._cli.print import echo, green, red, yellow
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.export import run_app_then_export_as_html
+from marimo._server.export._html_asset_server import HtmlAssetServer
from marimo._server.file_router import flatten_files
from marimo._server.files.directory_scanner import DirectoryScanner
from marimo._server.utils import asyncio_run
@@ -30,7 +27,6 @@ from marimo._utils.paths import marimo_package_path, maybe_make_dirs
if TYPE_CHECKING:
from collections.abc import Iterable
- from types import TracebackType
from marimo._cli.sandbox import SandboxMode
@@ -232,89 +228,6 @@ sys.stdout.write(result.text)
return result.stdout
-class _ThumbnailRequestHandler(SimpleHTTPRequestHandler):
- def do_GET(self) -> None: # noqa: N802
- if self.path.split("?", 1)[0] == "/__marimo_thumbnail__.html":
- html = getattr(self.server, "thumbnail_html", "")
- self.send_response(200)
- self.send_header("Content-Type", "text/html; charset=utf-8")
- self.send_header("Cache-Control", "no-store")
- self.end_headers()
- self.wfile.write(html.encode("utf-8"))
- return
- return super().do_GET()
-
- def log_message(self, format: str, *args: Any) -> None: # noqa: A002
- # Silence noisy server logs for CLI usage.
- del format
- del args
- return
-
-
-class _ThumbnailHTTPServer(ThreadingHTTPServer):
- # Set by _ThumbnailAssetServer to serve a fresh HTML document per notebook.
- thumbnail_html: str
-
-
-class _ThumbnailAssetServer(AbstractContextManager["_ThumbnailAssetServer"]):
- def __init__(self, *, directory: Path) -> None:
- self._directory = directory
- self._server: _ThumbnailHTTPServer | None = None
- self._thread: threading.Thread | None = None
-
- @property
- def base_url(self) -> str:
- assert self._server is not None
- host, port = self._server.server_address[:2]
- if isinstance(host, bytes):
- host = host.decode("utf-8")
- return f"http://{host}:{port}"
-
- @property
- def page_url(self) -> str:
- return f"{self.base_url}/__marimo_thumbnail__.html"
-
- def set_html(self, html: str) -> None:
- assert self._server is not None
- self._server.thumbnail_html = html
-
- def __enter__(self) -> _ThumbnailAssetServer:
- if not self._directory.is_dir():
- raise click.ClickException(
- f"Static assets not found at {self._directory}"
- )
-
- handler = partial(
- _ThumbnailRequestHandler, directory=str(self._directory)
- )
- self._server = _ThumbnailHTTPServer(("127.0.0.1", 0), handler)
- self._server.thumbnail_html = ""
-
- self._thread = threading.Thread(
- target=self._server.serve_forever, daemon=True
- )
- self._thread.start()
- return self
-
- def __exit__(
- self,
- exc_type: type[BaseException] | None,
- exc: BaseException | None,
- tb: TracebackType | None,
- ) -> None:
- del exc_type
- del exc
- del tb
- if self._server is not None:
- self._server.shutdown()
- self._server.server_close()
- self._server = None
- if self._thread is not None:
- self._thread.join(timeout=1)
- self._thread = None
- return None
-
-
class _SandboxVenvPool:
def __init__(self) -> None:
self._envs: dict[tuple[str, ...], tuple[str, str]] = {}
@@ -393,7 +306,9 @@ async def _generate_thumbnails(
_SandboxVenvPool() if use_per_notebook_sandbox else None
)
try:
- with _ThumbnailAssetServer(directory=static_dir) as server:
+ with HtmlAssetServer(
+ directory=static_dir, route="/__marimo_thumbnail__.html"
+ ) as server:
async with async_playwright() as playwright:
browser = await playwright.chromium.launch()
context = await browser.new_context(
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 631422e908..ac71ff9550 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -42,8 +42,12 @@ from marimo._utils.marimo_path import MarimoPath
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
+ from collections.abc import Mapping
+
+ from marimo._server.export._pdf_raster import PDFRasterizationOptions
from marimo._session.state.session_view import SessionView
from marimo._session.types import Session
+ from marimo._types.ids import CellId_t
@dataclass
@@ -213,6 +217,7 @@ async def run_app_then_export_as_pdf(
cli_args: SerializedCLIArgs,
argv: list[str] | None,
include_inputs: bool = True,
+ rasterization_options: PDFRasterizationOptions | None = None,
) -> tuple[bytes | None, bool]:
file_router = AppFileRouter.from_filename(filepath)
file_key = file_router.get_unique_file_key()
@@ -220,6 +225,7 @@ async def run_app_then_export_as_pdf(
file_manager = file_router.get_file_manager(file_key)
session_view: SessionView | None = None
+ png_fallbacks: Mapping[CellId_t, str] | None = None
did_error = False
if include_outputs:
@@ -233,9 +239,28 @@ async def run_app_then_export_as_pdf(
quiet=True,
)
+ if (
+ session_view is not None
+ and rasterization_options is not None
+ and rasterization_options.enabled
+ ):
+ from marimo._server.export._pdf_raster import (
+ collect_pdf_png_fallbacks,
+ )
+
+ png_fallbacks = await collect_pdf_png_fallbacks(
+ app=file_manager.app,
+ session_view=session_view,
+ filename=filepath.short_name,
+ filepath=filepath.absolute_name,
+ argv=argv,
+ options=rasterization_options,
+ )
+
pdf_data = Exporter().export_as_pdf(
app=file_manager.app,
session_view=session_view,
+ png_fallbacks=png_fallbacks,
include_inputs=include_inputs,
webpdf=webpdf,
)
diff --git a/marimo/_server/export/_html_asset_server.py b/marimo/_server/export/_html_asset_server.py
new file mode 100644
index 0000000000..ce72c3bec7
--- /dev/null
+++ b/marimo/_server/export/_html_asset_server.py
@@ -0,0 +1,102 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import threading
+from contextlib import AbstractContextManager
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from typing import TYPE_CHECKING, Any, cast
+
+if TYPE_CHECKING:
+ from pathlib import Path
+ from types import TracebackType
+
+
+class _HtmlAssetRequestHandler(SimpleHTTPRequestHandler):
+ def do_GET(self) -> None:
+ server = cast(_HtmlAssetHTTPServer, self.server)
+ route = self.path.split("?", 1)[0]
+ dynamic_route = server.dynamic_route
+ if route == dynamic_route:
+ with server.dynamic_html_lock:
+ html = server.dynamic_html
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ self.wfile.write(html.encode("utf-8"))
+ return
+ return super().do_GET()
+
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
+ del format
+ del args
+
+
+class _HtmlAssetHTTPServer(ThreadingHTTPServer):
+ dynamic_route: str
+ dynamic_html: str
+ dynamic_html_lock: threading.Lock
+
+
+class HtmlAssetServer(AbstractContextManager["HtmlAssetServer"]):
+ def __init__(self, *, directory: Path, route: str) -> None:
+ self._directory = directory
+ self._route = route if route.startswith("/") else f"/{route}"
+ self._server: _HtmlAssetHTTPServer | None = None
+ self._thread: threading.Thread | None = None
+
+ @property
+ def base_url(self) -> str:
+ if self._server is None:
+ raise RuntimeError("HTML asset server is not running")
+ host, port = self._server.server_address[:2]
+ if isinstance(host, bytes):
+ host = host.decode("utf-8")
+ return f"http://{host}:{port}"
+
+ @property
+ def page_url(self) -> str:
+ return f"{self.base_url}{self._route}"
+
+ def set_html(self, html: str) -> None:
+ if self._server is None:
+ raise RuntimeError("HTML asset server is not running")
+ with self._server.dynamic_html_lock:
+ self._server.dynamic_html = html
+
+ def __enter__(self) -> HtmlAssetServer: # noqa: PYI034
+ if not self._directory.is_dir():
+ raise RuntimeError(f"Static assets not found at {self._directory}")
+
+ handler = partial(
+ _HtmlAssetRequestHandler,
+ directory=str(self._directory),
+ )
+ self._server = _HtmlAssetHTTPServer(("127.0.0.1", 0), handler)
+ self._server.dynamic_route = self._route
+ self._server.dynamic_html = ""
+ self._server.dynamic_html_lock = threading.Lock()
+
+ self._thread = threading.Thread(
+ target=self._server.serve_forever,
+ daemon=True,
+ )
+ self._thread.start()
+ return self
+
+ def __exit__(
+ self,
+ _exc_type: type[BaseException] | None,
+ _exc: BaseException | None,
+ _tb: TracebackType | None,
+ ) -> None:
+ # Cleanup only. We intentionally do not suppress exceptions raised inside the with-block.
+
+ if self._server is not None:
+ self._server.shutdown()
+ self._server.server_close()
+ self._server = None
+ if self._thread is not None:
+ self._thread.join(timeout=1)
+ self._thread = None
diff --git a/marimo/_server/export/_live_notebook_server.py b/marimo/_server/export/_live_notebook_server.py
new file mode 100644
index 0000000000..4c70d38c7b
--- /dev/null
+++ b/marimo/_server/export/_live_notebook_server.py
@@ -0,0 +1,163 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import subprocess
+import sys
+import tempfile
+import time
+from contextlib import AbstractContextManager
+from pathlib import Path
+from urllib.error import URLError
+from urllib.request import urlopen
+
+from marimo import _loggers
+from marimo._utils.net import find_free_port
+
+LOGGER = _loggers.marimo_logger()
+
+_LIVE_SERVER_START_TIMEOUT_S = 90.0
+_LIVE_SERVER_POLL_INTERVAL_S = 0.2
+_LIVE_SERVER_SHUTDOWN_TIMEOUT_S = 5.0
+_LIVE_SERVER_DEFAULT_PORT = 2719
+
+
+class LiveNotebookServer(AbstractContextManager["LiveNotebookServer"]):
+ """Run a temporary headless marimo server for live output capture."""
+
+ def __init__(self, *, filepath: str, argv: list[str] | None) -> None:
+ self._filepath = filepath
+ self._argv = list(argv or [])
+ self._port = find_free_port(
+ _LIVE_SERVER_DEFAULT_PORT,
+ addr="127.0.0.1",
+ )
+ self._process: subprocess.Popen[str] | None = None
+ self._log_file: tempfile._TemporaryFileWrapper[str] | None = None
+
+ @property
+ def page_url(self) -> str:
+ return f"http://127.0.0.1:{self._port}"
+
+ @property
+ def health_url(self) -> str:
+ return f"{self.page_url}/health"
+
+ def __enter__(self) -> LiveNotebookServer:
+ """Start the server process and block until the health endpoint is ready."""
+
+ self._log_file = tempfile.NamedTemporaryFile(
+ mode="w+",
+ encoding="utf-8",
+ delete=False,
+ )
+ self._process = subprocess.Popen(
+ self._build_command(),
+ stdout=self._log_file,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ self._wait_until_ready()
+ return self
+
+ def __exit__(
+ self,
+ _exc_type: type[BaseException] | None,
+ _exc: BaseException | None,
+ _tb: object,
+ ) -> None:
+ """Terminate the server and clean up temporary log resources."""
+ # Cleanup only. We intentionally do not suppress exceptions raised
+ # inside the with-block.
+
+ if self._process is not None:
+ self._terminate_process(self._process)
+ self._process = None
+
+ if self._log_file is not None:
+ log_name = self._log_file.name
+ self._log_file.close()
+ try:
+ Path(log_name).unlink(missing_ok=True)
+ except OSError:
+ LOGGER.debug(
+ "Failed to clean up live capture server log file: %s",
+ log_name,
+ )
+ self._log_file = None
+
+ def _build_command(self) -> list[str]:
+ """Build the marimo CLI command used to launch the live notebook."""
+
+ command = [
+ sys.executable,
+ "-m",
+ "marimo",
+ "run",
+ self._filepath,
+ "--headless",
+ "--no-token",
+ "--no-skew-protection",
+ "--no-check",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(self._port),
+ ]
+ if self._argv:
+ command.extend(["--", *self._argv])
+ return command
+
+ def _wait_until_ready(self) -> None:
+ """Poll process and health endpoint until server is ready or times out."""
+
+ start = time.monotonic()
+ while time.monotonic() - start < _LIVE_SERVER_START_TIMEOUT_S:
+ process = self._process
+ if process is None:
+ raise RuntimeError("Live notebook server process is missing")
+ if process.poll() is not None:
+ logs = self._read_logs()
+ raise RuntimeError(
+ "Live notebook server exited before becoming ready."
+ + (f"\n\n{logs}" if logs else "")
+ )
+
+ try:
+ with urlopen(self.health_url, timeout=1) as response:
+ if response.status == 200:
+ return
+ except URLError:
+ pass
+
+ time.sleep(_LIVE_SERVER_POLL_INTERVAL_S)
+
+ logs = self._read_logs()
+ raise RuntimeError(
+ "Timed out waiting for live notebook server to become ready."
+ + (f"\n\n{logs}" if logs else "")
+ )
+
+ def _read_logs(self) -> str:
+ """Return recent process logs for startup/shutdown error reporting."""
+
+ log_file = self._log_file
+ if log_file is None:
+ return ""
+ log_file.flush()
+ log_file.seek(0)
+ logs = log_file.read()
+ if len(logs) > 4_000:
+ return logs[-4_000:]
+ return logs
+
+ def _terminate_process(self, process: subprocess.Popen[str]) -> None:
+ """Gracefully terminate the server process and force-kill if needed."""
+
+ if process.poll() is not None:
+ return
+ process.terminate()
+ try:
+ process.wait(timeout=_LIVE_SERVER_SHUTDOWN_TIMEOUT_S)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=_LIVE_SERVER_SHUTDOWN_TIMEOUT_S)
diff --git a/marimo/_server/export/_nbformat_png_fallbacks.py b/marimo/_server/export/_nbformat_png_fallbacks.py
new file mode 100644
index 0000000000..49b849d060
--- /dev/null
+++ b/marimo/_server/export/_nbformat_png_fallbacks.py
@@ -0,0 +1,88 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast
+
+from marimo._server.export._raster_mime import MIME_TYPES_REPLACED_BY_PNG
+from marimo._types.ids import CellId_t
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
+ from nbformat.notebooknode import NotebookNode # type: ignore
+
+
+_DISPLAY_OUTPUT_TYPES = {"display_data", "execute_result"}
+_PNG_DATA_URL_PREFIX = "data:image/png;base64,"
+
+
+def _to_png_payload(data_url_or_payload: str) -> str | None:
+ if data_url_or_payload.startswith(_PNG_DATA_URL_PREFIX):
+ return data_url_or_payload.removeprefix(_PNG_DATA_URL_PREFIX)
+ if data_url_or_payload.startswith("data:"):
+ return None
+ return data_url_or_payload
+
+
+def inject_png_fallbacks_into_notebook(
+ notebook: NotebookNode,
+ png_fallbacks: Mapping[CellId_t, str],
+) -> int:
+ """Inject image/png fallbacks into a notebook node by code-cell id."""
+ injected_count = 0
+
+ cells = notebook.get("cells", [])
+ if not isinstance(cells, list):
+ return 0
+
+ for cell in cells:
+ if not isinstance(cell, dict):
+ continue
+ if cell.get("cell_type") != "code":
+ continue
+
+ raw_cell_id = cell.get("id")
+ if not isinstance(raw_cell_id, str):
+ continue
+ cell_id = cast(CellId_t, raw_cell_id)
+
+ data_url = png_fallbacks.get(cell_id)
+ if not data_url:
+ continue
+
+ png_payload = _to_png_payload(data_url)
+ if png_payload is None:
+ continue
+
+ outputs = cell.get("outputs")
+ if not isinstance(outputs, list):
+ continue
+
+ display_output: dict[str, Any] | None = None
+ for output in outputs:
+ if not isinstance(output, dict):
+ continue
+ output_type = output.get("output_type")
+ if output_type in _DISPLAY_OUTPUT_TYPES:
+ display_output = output
+ break
+
+ if display_output is None:
+ display_output = {
+ "output_type": "display_data",
+ "data": {},
+ "metadata": {},
+ }
+ outputs.append(display_output)
+
+ data = display_output.get("data")
+ if not isinstance(data, dict):
+ display_output["data"] = {}
+ data = cast(dict[str, Any], display_output["data"])
+
+ for mime_type in MIME_TYPES_REPLACED_BY_PNG:
+ data.pop(mime_type, None)
+ data["image/png"] = png_payload
+ injected_count += 1
+
+ return injected_count
diff --git a/marimo/_server/export/_pdf_raster.py b/marimo/_server/export/_pdf_raster.py
new file mode 100644
index 0000000000..2c556b94df
--- /dev/null
+++ b/marimo/_server/export/_pdf_raster.py
@@ -0,0 +1,660 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import json
+from copy import deepcopy
+from dataclasses import dataclass
+from html import unescape
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from marimo import _loggers
+from marimo._config.config import DisplayConfig
+from marimo._config.manager import get_default_config_manager
+from marimo._server.export._html_asset_server import HtmlAssetServer
+from marimo._server.export._live_notebook_server import LiveNotebookServer
+from marimo._server.export._raster_mime import (
+ TEXT_HTML,
+ TEXT_MARKDOWN,
+ TEXT_PLAIN,
+ VEGA_MIME_TYPES,
+)
+from marimo._server.models.export import ExportAsHTMLRequest
+from marimo._types.ids import CellId_t
+from marimo._utils.paths import marimo_package_path
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from marimo._ast.app import InternalApp
+ from marimo._session.state.session_view import SessionView
+
+LOGGER = _loggers.marimo_logger()
+
+MIMEBUNDLE_TYPE = "application/vnd.marimo+mimebundle"
+MARIMO_COMPONENT_MARKERS: tuple[str, ...] = (
+ "<marimo-",
+ "&lt;marimo-",
+)
+ANYWIDGET_COMPONENT_MARKERS: tuple[str, ...] = (
+ "<marimo-anywidget",
+ "&lt;marimo-anywidget",
+)
+EMBEDDED_VEGA_MARKERS: tuple[str, ...] = tuple(VEGA_MIME_TYPES)
+
+_READINESS_TIMEOUT_MS = 90_000
+_NETWORK_IDLE_TIMEOUT_MS = 10_000
+_NAVIGATION_SETTLE_TIMEOUT_MS = 30_000
+_DYNAMIC_OUTPUT_EXTRA_WAIT_MS = 10_000
+_VIEWPORT_WIDTH = 1440
+_VIEWPORT_HEIGHT = 1000
+
+WAIT_FOR_PAGE_READY = r"""
+() => {
+ const root = document.getElementById("root");
+ if (!root) return false;
+
+ const cells = document.querySelectorAll('div[id^="cell-"]');
+ if (cells.length === 0) return false;
+
+ return root.childElementCount > 0;
+}
+"""
+
+WAIT_FOR_NEXT_PAINT = r"""
+() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+})
+"""
+
+
+@dataclass(frozen=True)
+class PDFRasterizationOptions:
+ enabled: bool = True
+ scale: float = 4.0
+ server_mode: str = "static"
+
+
+CaptureExpectation = Literal["anywidget", "vega"]
+
+
+@dataclass(frozen=True)
+class _RasterTarget:
+ cell_id: CellId_t
+ expects: tuple[CaptureExpectation, ...]
+
+
+def _contains_marker(content: Any, markers: tuple[str, ...]) -> bool:
+ """Return whether any string payload contains one of the markers."""
+
+ def _contains(value: str) -> bool:
+ return any(marker in value for marker in markers)
+
+ if isinstance(content, list):
+ return any(
+ isinstance(item, str) and _contains(item) for item in content
+ )
+ return isinstance(content, str) and _contains(content)
+
+
+def _dedupe_strings(values: Sequence[str]) -> tuple[str, ...]:
+ return tuple(dict.fromkeys(values))
+
+
+def _load_mimebundle(data: Any) -> dict[str, Any] | None:
+ if isinstance(data, dict):
+ return data
+
+ if isinstance(data, str):
+ try:
+ loaded = json.loads(data)
+ except json.JSONDecodeError:
+ return None
+ if isinstance(loaded, dict):
+ return loaded
+
+ return None
+
+
+def _should_rasterize_output(mimetype: str, data: Any) -> bool:
+ """Return whether this output is eligible for PNG fallback capture."""
+
+ if mimetype in VEGA_MIME_TYPES:
+ return True
+
+ if mimetype in {TEXT_HTML, TEXT_PLAIN, TEXT_MARKDOWN}:
+ return _contains_marker(data, MARIMO_COMPONENT_MARKERS)
+
+ return False
+
+
+def _build_target_from_mimebundle(
+ cell_id: CellId_t,
+ mimebundle: dict[str, Any],
+) -> _RasterTarget | None:
+ """Build capture metadata for a cell emitting a MIME bundle output."""
+
+ should_capture = False
+ expects: list[CaptureExpectation] = []
+
+ for mimetype, content in mimebundle.items():
+ if _should_rasterize_output(mimetype, content):
+ should_capture = True
+ if _contains_marker(content, ANYWIDGET_COMPONENT_MARKERS):
+ expects.append("anywidget")
+ if mimetype in VEGA_MIME_TYPES or _contains_marker(
+ content, EMBEDDED_VEGA_MARKERS
+ ):
+ expects.append("vega")
+
+ if not should_capture:
+ return None
+
+ return _RasterTarget(
+ cell_id=cell_id,
+ expects=cast(tuple[CaptureExpectation, ...], _dedupe_strings(expects)),
+ )
+
+
+def _build_target_from_output(
+ cell_id: CellId_t,
+ *,
+ mimetype: str,
+ data: Any,
+) -> _RasterTarget | None:
+ """Build capture metadata for a non-mimebundle output."""
+
+ if not _should_rasterize_output(mimetype, data):
+ return None
+
+ expects: list[CaptureExpectation] = []
+ if _contains_marker(data, ANYWIDGET_COMPONENT_MARKERS):
+ expects.append("anywidget")
+ if mimetype in VEGA_MIME_TYPES or _contains_marker(
+ data, EMBEDDED_VEGA_MARKERS
+ ):
+ expects.append("vega")
+
+ return _RasterTarget(
+ cell_id=cell_id,
+ expects=cast(tuple[CaptureExpectation, ...], _dedupe_strings(expects)),
+ )
+
+
+def _collect_raster_targets(session_view: SessionView) -> list[_RasterTarget]:
+ """Collect capture targets from the current executed session outputs."""
+
+ targets: list[_RasterTarget] = []
+
+ for cell_id, cell_notification in session_view.cell_notifications.items():
+ output = cell_notification.output
+ if output is None or output.data is None:
+ continue
+
+ if output.mimetype == MIMEBUNDLE_TYPE:
+ mimebundle = _load_mimebundle(output.data)
+ if mimebundle is None:
+ continue
+ target = _build_target_from_mimebundle(cell_id, mimebundle)
+ if target is not None:
+ targets.append(target)
+ continue
+
+ target = _build_target_from_output(
+ cell_id,
+ mimetype=output.mimetype,
+ data=output.data,
+ )
+ if target is not None:
+ targets.append(target)
+
+ return targets
+
+
+def _sort_targets_by_notebook_order(
+ session_view: SessionView,
+ targets: list[_RasterTarget],
+) -> list[_RasterTarget]:
+ """Sort targets in notebook order so capture sequencing is deterministic."""
+
+ if session_view.cell_ids is None:
+ return targets
+
+ order = {
+ cell_id: index
+ for index, cell_id in enumerate(session_view.cell_ids.cell_ids)
+ }
+ fallback_index = len(order)
+ return sorted(
+ targets,
+ key=lambda target: order.get(target.cell_id, fallback_index),
+ )
+
+
+def _promote_text_output_for_capture(output: Any) -> None:
+ if not _contains_marker(output.data, MARIMO_COMPONENT_MARKERS):
+ return
+ output.mimetype = TEXT_HTML
+ output.data = _unescape_component_markup(output.data)
+
+
+def _promote_mimebundle_output_for_capture(output: Any) -> None:
+ """Ensure mimebundle component markup is available as unescaped text/html."""
+
+ mimebundle = _load_mimebundle(output.data)
+ if mimebundle is None:
+ return
+
+ html_data = mimebundle.get(TEXT_HTML)
+ if html_data is not None and _contains_marker(
+ html_data, MARIMO_COMPONENT_MARKERS
+ ):
+ mimebundle[TEXT_HTML] = _unescape_component_markup(html_data)
+ output.data = mimebundle
+ return
+
+ plain_data = mimebundle.get(TEXT_PLAIN)
+ if plain_data is None or not _contains_marker(
+ plain_data, MARIMO_COMPONENT_MARKERS
+ ):
+ markdown_data = mimebundle.get(TEXT_MARKDOWN)
+ if markdown_data is None or not _contains_marker(
+ markdown_data, MARIMO_COMPONENT_MARKERS
+ ):
+ return
+ mimebundle[TEXT_HTML] = _unescape_component_markup(markdown_data)
+ output.data = mimebundle
+ return
+
+ mimebundle[TEXT_HTML] = _unescape_component_markup(plain_data)
+ output.data = mimebundle
+
+
+def _promote_component_markup_for_capture(
+ session_view: SessionView,
+ targets: list[_RasterTarget],
+) -> SessionView:
+ """Return a copied session view with target component outputs normalized."""
+
+ capture_view = deepcopy(session_view)
+
+ for target in targets:
+ cell_notification = capture_view.cell_notifications.get(target.cell_id)
+ if cell_notification is None or cell_notification.output is None:
+ continue
+
+ output = cell_notification.output
+ if output.mimetype in {TEXT_HTML, TEXT_PLAIN, TEXT_MARKDOWN}:
+ _promote_text_output_for_capture(output)
+ continue
+
+ if output.mimetype != MIMEBUNDLE_TYPE:
+ continue
+
+ _promote_mimebundle_output_for_capture(output)
+
+ return capture_view
+
+
+def _unescape_component_markup(data: Any) -> Any:
+ if isinstance(data, str):
+ return unescape(data)
+ if isinstance(data, list):
+ return [
+ unescape(item) if isinstance(item, str) else item for item in data
+ ]
+ return data
+
+
+def _to_display_config(filepath: str | None) -> DisplayConfig:
+ """Resolve display config for exporter rendering settings."""
+
+ config = get_default_config_manager(current_path=filepath).get_config()
+ return cast(DisplayConfig, config["display"])
+
+
+def _to_data_url(image: bytes) -> str:
+ encoded = base64.b64encode(image).decode("ascii")
+ return f"data:image/png;base64,{encoded}"
+
+
+async def _collect_static_captures(
+ *,
+ app: InternalApp,
+ session_view: SessionView,
+ filename: str | None,
+ filepath: str | None,
+ options: PDFRasterizationOptions,
+ static_targets: list[_RasterTarget],
+) -> dict[CellId_t, str]:
+ """Capture PNG fallbacks from exported static HTML for non-live targets."""
+
+ from marimo._server.export.exporter import Exporter
+
+ LOGGER.debug(
+ "Raster capture static phase: %s target(s), scale=%s",
+ len(static_targets),
+ options.scale,
+ )
+
+ static_dir = marimo_package_path() / "_static"
+ with HtmlAssetServer(
+ directory=static_dir,
+ route="/__marimo_pdf_raster__.html",
+ ) as server:
+ capture_view = _promote_component_markup_for_capture(
+ session_view,
+ static_targets,
+ )
+ html, _download_filename = Exporter().export_as_html(
+ filename=filename,
+ app=app,
+ session_view=capture_view,
+ display_config=_to_display_config(filepath),
+ request=ExportAsHTMLRequest(
+ download=False,
+ files=[],
+ include_code=True,
+ asset_url=server.base_url,
+ ),
+ )
+ server.set_html(html)
+ captures = await _capture_pngs_from_page(
+ page_url=server.page_url,
+ targets=static_targets,
+ scale=options.scale,
+ )
+ LOGGER.debug(
+ "Raster capture static phase complete: %s/%s captured",
+ len(captures),
+ len(static_targets),
+ )
+ return captures
+
+
+async def _collect_live_captures(
+ *,
+ filepath: str | None,
+ argv: list[str] | None,
+ options: PDFRasterizationOptions,
+ live_targets: list[_RasterTarget],
+) -> dict[CellId_t, str]:
+ """Capture PNG fallbacks from a live notebook runtime when required."""
+
+ if not filepath:
+ LOGGER.debug(
+ "Raster capture live phase skipped: no filepath provided."
+ )
+ return {}
+
+ LOGGER.debug(
+ "Raster capture live phase: %s target(s), scale=%s",
+ len(live_targets),
+ options.scale,
+ )
+ captures = await _capture_pngs_from_live_page(
+ filepath=filepath,
+ targets=live_targets,
+ scale=options.scale,
+ argv=argv,
+ )
+ LOGGER.debug(
+ "Raster capture live phase complete: %s/%s captured",
+ len(captures),
+ len(live_targets),
+ )
+ return captures
+
+
+async def collect_pdf_png_fallbacks(
+ *,
+ app: InternalApp,
+ session_view: SessionView,
+ filename: str | None,
+ filepath: str | None,
+ argv: list[str] | None = None,
+ options: PDFRasterizationOptions,
+) -> dict[CellId_t, str]:
+ """Collect per-cell PNG fallbacks to inject before nbconvert PDF export."""
+
+ if not options.enabled:
+ LOGGER.debug("Raster capture disabled by options.")
+ return {}
+
+ targets = _collect_raster_targets(session_view)
+ if not targets:
+ LOGGER.debug("Raster capture skipped: no eligible outputs found.")
+ return {}
+
+ targets = _sort_targets_by_notebook_order(session_view, targets)
+ server_mode = options.server_mode.lower()
+ if server_mode not in {"static", "live"}:
+ LOGGER.warning(
+ "Unknown raster server mode '%s'; defaulting to static.",
+ options.server_mode,
+ )
+ server_mode = "static"
+
+ LOGGER.debug(
+ "Raster capture planning: total=%s server_mode=%s",
+ len(targets),
+ server_mode,
+ )
+
+ if server_mode == "live":
+ LOGGER.debug("Raster capture strategy: live-only.")
+ captures = await _collect_live_captures(
+ filepath=filepath,
+ argv=argv,
+ options=options,
+ live_targets=targets,
+ )
+ else:
+ LOGGER.debug("Raster capture strategy: static-only.")
+ captures = await _collect_static_captures(
+ app=app,
+ session_view=session_view,
+ filename=filename,
+ filepath=filepath,
+ options=options,
+ static_targets=targets,
+ )
+
+ LOGGER.debug(
+ "Raster capture complete: %s/%s outputs captured.",
+ len(captures),
+ len(targets),
+ )
+ return captures
+
+
+async def _wait_for_network_idle(
+ page: Any,
+ *,
+ timeout_ms: int,
+ timeout_error: type[Exception],
+) -> None:
+ """Best-effort network-idle wait that never fails capture flow."""
+
+ try:
+ await page.wait_for_load_state("networkidle", timeout=timeout_ms)
+ except timeout_error:
+ return
+
+
+async def _wait_for_navigation_settled(
+ *,
+ page: Any,
+ timeout_error: type[Exception],
+) -> None:
+ """Settle the page by waiting for load states and a fixed quiet period."""
+
+ for state in ("domcontentloaded", "load", "networkidle"):
+ try:
+ await page.wait_for_load_state(
+ state,
+ timeout=_NAVIGATION_SETTLE_TIMEOUT_MS,
+ )
+ except timeout_error:
+ continue
+ await page.wait_for_timeout(_DYNAMIC_OUTPUT_EXTRA_WAIT_MS)
+
+
+async def _wait_for_target_ready(
+ *,
+ page: Any,
+ target: _RasterTarget,
+ locator: Any,
+ timeout_error: type[Exception],
+) -> bool:
+ """Wait for a target output to become visible and then stabilize."""
+
+ try:
+ await locator.wait_for(
+ state="visible",
+ timeout=_READINESS_TIMEOUT_MS,
+ )
+ await locator.scroll_into_view_if_needed(
+ timeout=_READINESS_TIMEOUT_MS,
+ )
+ await page.evaluate(WAIT_FOR_NEXT_PAINT)
+ await _wait_for_network_idle(
+ page,
+ timeout_ms=_NETWORK_IDLE_TIMEOUT_MS,
+ timeout_error=timeout_error,
+ )
+ if target.expects:
+ await _wait_for_navigation_settled(
+ page=page,
+ timeout_error=timeout_error,
+ )
+
+ await _wait_for_network_idle(
+ page,
+ timeout_ms=_NETWORK_IDLE_TIMEOUT_MS,
+ timeout_error=timeout_error,
+ )
+ await page.evaluate(WAIT_FOR_NEXT_PAINT)
+ except timeout_error:
+ LOGGER.debug(
+ "Raster target %s timed out while waiting for visibility/readiness.",
+ target.cell_id,
+ )
+ return False
+ else:
+ return True
+
+
+async def _capture_pngs_from_page(
+ *,
+ page_url: str,
+ targets: list[_RasterTarget],
+ scale: float,
+) -> dict[CellId_t, str]:
+ """Capture PNG screenshots for target outputs from a single page URL."""
+
+ from playwright.async_api import ( # type: ignore[import-not-found]
+ TimeoutError as PlaywrightTimeoutError,
+ async_playwright,
+ )
+
+ captures: dict[CellId_t, str] = {}
+ device_scale_factor = max(1.0, scale)
+
+ LOGGER.debug(
+ "Raster page capture start: url=%s targets=%s scale=%s",
+ page_url,
+ len(targets),
+ scale,
+ )
+
+ async with async_playwright() as playwright:
+ browser = await playwright.chromium.launch()
+ context = await browser.new_context(
+ viewport={
+ "width": _VIEWPORT_WIDTH,
+ "height": _VIEWPORT_HEIGHT,
+ },
+ device_scale_factor=device_scale_factor,
+ )
+ page = await context.new_page()
+ await page.goto(
+ page_url,
+ wait_until="domcontentloaded",
+ timeout=_READINESS_TIMEOUT_MS,
+ )
+ await _wait_for_network_idle(
+ page,
+ timeout_ms=_NETWORK_IDLE_TIMEOUT_MS,
+ timeout_error=PlaywrightTimeoutError,
+ )
+ await page.wait_for_function(
+ WAIT_FOR_PAGE_READY,
+ timeout=_READINESS_TIMEOUT_MS,
+ )
+ await _wait_for_network_idle(
+ page,
+ timeout_ms=_NETWORK_IDLE_TIMEOUT_MS,
+ timeout_error=PlaywrightTimeoutError,
+ )
+
+ for target in targets:
+ locator = page.locator(f"#output-{target.cell_id}").first
+ if not await _wait_for_target_ready(
+ page=page,
+ target=target,
+ locator=locator,
+ timeout_error=PlaywrightTimeoutError,
+ ):
+ LOGGER.debug(
+ "Raster target skipped: cell_id=%s",
+ target.cell_id,
+ )
+ continue
+
+ try:
+ await page.evaluate(WAIT_FOR_NEXT_PAINT)
+ image = await locator.screenshot(
+ type="png",
+ animations="disabled",
+ timeout=_READINESS_TIMEOUT_MS,
+ )
+ except PlaywrightTimeoutError:
+ LOGGER.debug(
+ "Raster screenshot timed out: cell_id=%s",
+ target.cell_id,
+ )
+ continue
+
+ captures[target.cell_id] = _to_data_url(image)
+ LOGGER.debug(
+ "Raster target captured: cell_id=%s",
+ target.cell_id,
+ )
+
+ await context.close()
+ await browser.close()
+
+ LOGGER.debug(
+ "Raster page capture complete: %s/%s captured",
+ len(captures),
+ len(targets),
+ )
+ return captures
+
+
+async def _capture_pngs_from_live_page(
+ *,
+ filepath: str,
+ targets: list[_RasterTarget],
+ scale: float,
+ argv: list[str] | None,
+) -> dict[CellId_t, str]:
+ """Capture outputs by running notebook in a live marimo server process."""
+
+ with LiveNotebookServer(filepath=filepath, argv=argv) as server:
+ return await _capture_pngs_from_page(
+ page_url=server.page_url,
+ targets=targets,
+ scale=scale,
+ )
diff --git a/marimo/_server/export/_raster_mime.py b/marimo/_server/export/_raster_mime.py
new file mode 100644
index 0000000000..99e1aff47b
--- /dev/null
+++ b/marimo/_server/export/_raster_mime.py
@@ -0,0 +1,24 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Final
+
+from marimo._messaging.mimetypes import KnownMimeType
+
+TEXT_HTML: Final[KnownMimeType] = "text/html"
+TEXT_PLAIN: Final[KnownMimeType] = "text/plain"
+TEXT_MARKDOWN: Final[KnownMimeType] = "text/markdown"
+
+VEGA_MIME_TYPES: Final[set[KnownMimeType]] = {
+ "application/vnd.vegalite.v5+json",
+ "application/vnd.vega.v5+json",
+ "application/vnd.vegalite.v6+json",
+ "application/vnd.vega.v6+json",
+}
+
+MIME_TYPES_REPLACED_BY_PNG: Final[set[KnownMimeType]] = {
+ TEXT_HTML,
+ TEXT_PLAIN,
+ TEXT_MARKDOWN,
+ *VEGA_MIME_TYPES,
+}
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 960f31a770..2a56bc5690 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -6,7 +6,7 @@ import base64
import mimetypes
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from typing import Literal, Optional, cast
+from typing import TYPE_CHECKING, Literal, Optional, cast
from marimo import _loggers
from marimo._ast.app import InternalApp
@@ -42,6 +42,7 @@ from marimo._session.state.serialize import (
serialize_session_view,
)
from marimo._session.state.session_view import SessionView
+from marimo._types.ids import CellId_t
from marimo._utils import async_path
from marimo._utils.code import hash_code
from marimo._utils.data_uri import build_data_url
@@ -49,6 +50,9 @@ from marimo._utils.marimo_path import MarimoPath
from marimo._utils.paths import marimo_package_path
from marimo._version import __version__
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
LOGGER = _loggers.marimo_logger()
# Root directory for static assets
@@ -314,6 +318,7 @@ class Exporter:
*,
app: InternalApp,
session_view: SessionView | None,
+ png_fallbacks: Mapping[CellId_t, str] | None = None,
webpdf: bool,
include_inputs: bool = True,
) -> bytes | None:
@@ -322,6 +327,8 @@ class Exporter:
Args:
app: The app to export
session_view: The session view to export. If None, outputs are not included.
+ png_fallbacks: Optional cell-id keyed image/png fallbacks to
+ inject into notebook outputs before nbconvert.
include_inputs: Whether to include code cell inputs in the export.
webpdf: If False, tries standard PDF export (pandoc + TeX) first,
falling back to webpdf on failure. If True, uses webpdf
@@ -348,6 +355,15 @@ class Exporter:
import nbformat
notebook = nbformat.reads(ipynb_json_str, as_version=4) # type: ignore[no-untyped-call]
+ if png_fallbacks:
+ from marimo._server.export._nbformat_png_fallbacks import (
+ inject_png_fallbacks_into_notebook,
+ )
+
+ inject_png_fallbacks_into_notebook(
+ notebook,
+ png_fallbacks=png_fallbacks,
+ )
# Try standard PDF export first (requires pandoc + TeX)
# and fall back to webpdf if it fails
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index b98a0cc572..eafc6dc2ed 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any
import click
import pytest
+from marimo._cli.export.commands import pdf
from marimo._dependencies.dependencies import DependencyManager
from marimo._utils import async_path
from marimo._utils.platform import is_windows
@@ -843,6 +844,22 @@ class TestExportIpynb:
class TestExportPDF:
+ @staticmethod
+ def test_export_pdf_rasterize_outputs_default_enabled() -> None:
+ rasterize_option = next(
+ param for param in pdf.params if param.name == "rasterize_outputs"
+ )
+ assert isinstance(rasterize_option, click.Option)
+ assert rasterize_option.default is True
+
+ @staticmethod
+ def test_export_pdf_raster_server_default_static() -> None:
+ raster_server_option = next(
+ param for param in pdf.params if param.name == "raster_server"
+ )
+ assert isinstance(raster_server_option, click.Option)
+ assert raster_server_option.default == "static"
+
@pytest.mark.skipif(
DependencyManager.nbformat.has() and DependencyManager.nbconvert.has(),
reason="This test expects PDF export deps to be missing.",
@@ -864,6 +881,62 @@ class TestExportPDF:
assert "nbconvert" in stderr
assert "pip install" in stderr
+ @staticmethod
+ def test_export_pdf_rasterize_requires_outputs(
+ temp_marimo_file: str,
+ ) -> None:
+ output_file = temp_marimo_file.replace(".py", ".pdf")
+ p = _run_export(
+ "pdf",
+ temp_marimo_file,
+ "--output",
+ output_file,
+ "--no-include-outputs",
+ "--rasterize-outputs",
+ "--no-sandbox",
+ )
+ _assert_failure(p)
+ stderr = p.stderr.decode()
+ assert "Rasterization options require --include-outputs." in stderr
+
+ @staticmethod
+ def test_export_pdf_raster_scale_requires_outputs(
+ temp_marimo_file: str,
+ ) -> None:
+ output_file = temp_marimo_file.replace(".py", ".pdf")
+ p = _run_export(
+ "pdf",
+ temp_marimo_file,
+ "--output",
+ output_file,
+ "--no-include-outputs",
+ "--raster-scale",
+ "2",
+ "--no-sandbox",
+ )
+ _assert_failure(p)
+ stderr = p.stderr.decode()
+ assert "Rasterization options require --include-outputs." in stderr
+
+ @staticmethod
+ def test_export_pdf_raster_server_requires_outputs(
+ temp_marimo_file: str,
+ ) -> None:
+ output_file = temp_marimo_file.replace(".py", ".pdf")
+ p = _run_export(
+ "pdf",
+ temp_marimo_file,
+ "--output",
+ output_file,
+ "--no-include-outputs",
+ "--raster-server",
+ "live",
+ "--no-sandbox",
+ )
+ _assert_failure(p)
+ stderr = p.stderr.decode()
+ assert "Rasterization options require --include-outputs." in stderr
+
@pytest.mark.skipif(
not DependencyManager.playwright.has(),
diff --git a/tests/_server/export/test_nbformat_png_fallbacks.py b/tests/_server/export/test_nbformat_png_fallbacks.py
new file mode 100644
index 0000000000..ff6b5d0ffc
--- /dev/null
+++ b/tests/_server/export/test_nbformat_png_fallbacks.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._server.export._nbformat_png_fallbacks import (
+ inject_png_fallbacks_into_notebook,
+)
+
+nbformat = pytest.importorskip("nbformat")
+
+
+def test_inject_png_fallbacks_replaces_rasterized_mimetypes() -> None:
+ notebook = nbformat.v4.new_notebook()
+ cell = nbformat.v4.new_code_cell("print('x')", id="cell-1")
+ cell.outputs = [
+ nbformat.v4.new_output(
+ "display_data",
+ data={
+ "text/html": "<div>hello</div>",
+ "text/plain": "hello",
+ "application/vnd.vega.v5+json": {"mark": "point"},
+ },
+ metadata={},
+ )
+ ]
+ notebook.cells = [cell]
+
+ injected = inject_png_fallbacks_into_notebook(
+ notebook,
+ png_fallbacks={"cell-1": "data:image/png;base64,ZmFrZQ=="},
+ )
+
+ assert injected == 1
+ data = notebook.cells[0].outputs[0]["data"]
+ assert "text/html" not in data
+ assert "text/plain" not in data
+ assert "application/vnd.vega.v5+json" not in data
+ assert data["image/png"] == "ZmFrZQ=="
+
+
+def test_inject_png_fallbacks_appends_display_output_when_missing() -> None:
+ notebook = nbformat.v4.new_notebook()
+ cell = nbformat.v4.new_code_cell("print('x')", id="cell-2")
+ cell.outputs = []
+ notebook.cells = [cell]
+
+ injected = inject_png_fallbacks_into_notebook(
+ notebook,
+ png_fallbacks={"cell-2": "data:image/png;base64,YWJj"},
+ )
+
+ assert injected == 1
+ assert len(notebook.cells[0].outputs) == 1
+ output = notebook.cells[0].outputs[0]
+ assert output["output_type"] == "display_data"
+ assert output["data"]["image/png"] == "YWJj"
+
+
+def test_inject_png_fallbacks_keeps_existing_plain_payload() -> None:
+ notebook = nbformat.v4.new_notebook()
+ cell = nbformat.v4.new_code_cell("print('x')", id="cell-3")
+ cell.outputs = [
+ nbformat.v4.new_output("display_data", data={}, metadata={})
+ ]
+ notebook.cells = [cell]
+
+ injected = inject_png_fallbacks_into_notebook(
+ notebook,
+ png_fallbacks={"cell-3": "YWJj"},
+ )
+
+ assert injected == 1
+ assert notebook.cells[0].outputs[0]["data"]["image/png"] == "YWJj"
diff --git a/tests/_server/export/test_pdf_raster.py b/tests/_server/export/test_pdf_raster.py
new file mode 100644
index 0000000000..54d8465a58
--- /dev/null
+++ b/tests/_server/export/test_pdf_raster.py
@@ -0,0 +1,371 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+from marimo._ast.app import App, InternalApp
+from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.notification import (
+ CellNotification,
+ UpdateCellIdsNotification,
+)
+from marimo._server.export import _pdf_raster
+from marimo._session.state.session_view import SessionView
+
+
+def _cell_notification(
+ *,
+ cell_id: str,
+ mimetype: str,
+ data: object,
+) -> CellNotification:
+ return CellNotification(
+ cell_id=cell_id,
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype=mimetype,
+ data=data,
+ ),
+ timestamp=0,
+ )
+
+
+def test_collect_raster_targets_detects_html_vega_and_anywidget() -> None:
+ session_view = SessionView()
+ session_view.cell_notifications["1"] = _cell_notification(
+ cell_id="1",
+ mimetype="text/html",
+ data="<div>hello</div>",
+ )
+ session_view.cell_notifications["2"] = _cell_notification(
+ cell_id="2",
+ mimetype="application/vnd.marimo+mimebundle",
+ data={
+ "application/vnd.vegalite.v5+json": {"mark": "point"},
+ "text/plain": "vega",
+ },
+ )
+ session_view.cell_notifications["3"] = _cell_notification(
+ cell_id="3",
+ mimetype="text/markdown",
+ data=(
+ "&lt;marimo-anywidget "
+ 'data-initial-value=\'{"model_id":"model-1"}\''
+ "&gt;&lt;/marimo-anywidget&gt;"
+ ),
+ )
+ session_view.cell_notifications["4"] = _cell_notification(
+ cell_id="4",
+ mimetype="text/plain",
+ data="plain text",
+ )
+ session_view.cell_notifications["5"] = _cell_notification(
+ cell_id="5",
+ mimetype="text/html",
+ data=("<marimo-stack>application/vnd.vegalite.v6+json</marimo-stack>"),
+ )
+
+ targets = _pdf_raster._collect_raster_targets(session_view)
+
+ by_id = {target.cell_id: target for target in targets}
+ assert set(by_id) == {"2", "3", "5"}
+ assert by_id["2"].expects == ("vega",)
+ assert by_id["3"].expects == ("anywidget",)
+ assert by_id["5"].expects == ("vega",)
+
+
+def test_collect_pdf_png_fallbacks_mixed_targets_use_static_by_default() -> (
+ None
+):
+ session_view = SessionView()
+ original_anywidget = (
+ '&lt;marimo-anywidget data-initial-value=\'{"model_id":"m-live"}\''
+ "&gt;&lt;/marimo-anywidget&gt;"
+ )
+ session_view.cell_notifications["1"] = _cell_notification(
+ cell_id="1",
+ mimetype="text/plain",
+ data=original_anywidget,
+ )
+ session_view.cell_notifications["2"] = _cell_notification(
+ cell_id="2",
+ mimetype="text/html",
+ data="<marimo-slider></marimo-slider>",
+ )
+ session_view.cell_notifications["3"] = _cell_notification(
+ cell_id="3",
+ mimetype="application/vnd.marimo+mimebundle",
+ data={
+ "application/vnd.vegalite.v6+json": {"mark": "point"},
+ "text/plain": "vega",
+ },
+ )
+ session_view.cell_ids = UpdateCellIdsNotification(cell_ids=["3", "2", "1"])
+ app = InternalApp(App())
+ live_capture_mock = AsyncMock(
+ side_effect=AssertionError(
+ "live capture should not run for default static mode"
+ )
+ )
+
+ class _FakeServer:
+ base_url = "http://127.0.0.1:1234"
+ page_url = "http://127.0.0.1:1234/__marimo_pdf_raster__.html"
+
+ def __enter__(self) -> Any:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ del args
+
+ def set_html(self, html: str) -> None:
+ assert "<html" in html
+
+ async def _capture_static(
+ *,
+ page_url: str,
+ targets: list[_pdf_raster._RasterTarget],
+ scale: float,
+ ) -> dict[str, str]:
+ assert page_url.endswith("__marimo_pdf_raster__.html")
+ assert scale == 4.0
+ assert [target.cell_id for target in targets] == ["3", "2", "1"]
+ return {
+ "3": "data:image/png;base64,c3RhdGljMw==",
+ "2": "data:image/png;base64,c3RhdGljMg==",
+ "1": "data:image/png;base64,c3RhdGljMQ==",
+ }
+
+ def _fake_export_as_html(*args: Any, **kwargs: Any) -> tuple[str, str]:
+ del args
+ del kwargs
+ return "<html></html>", "demo.html"
+
+ async def _run() -> dict[str, str]:
+ with (
+ patch.object(
+ _pdf_raster,
+ "HtmlAssetServer",
+ return_value=_FakeServer(),
+ ),
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_page",
+ side_effect=_capture_static,
+ ),
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_live_page",
+ live_capture_mock,
+ ),
+ patch(
+ "marimo._server.export.exporter.Exporter.export_as_html",
+ side_effect=_fake_export_as_html,
+ ),
+ ):
+ return await _pdf_raster.collect_pdf_png_fallbacks(
+ app=app,
+ session_view=session_view,
+ filename="demo.py",
+ filepath="demo.py",
+ argv=["--arg", "value"],
+ options=_pdf_raster.PDFRasterizationOptions(),
+ )
+
+ captures = asyncio.run(_run())
+ assert captures == {
+ "1": "data:image/png;base64,c3RhdGljMQ==",
+ "2": "data:image/png;base64,c3RhdGljMg==",
+ "3": "data:image/png;base64,c3RhdGljMw==",
+ }
+ live_capture_mock.assert_not_awaited()
+ output = session_view.cell_notifications["1"].output
+ assert output is not None
+ assert output.mimetype == "text/plain"
+ assert output.data == original_anywidget
+
+
+def test_collect_pdf_png_fallbacks_static_only_uses_static_capture() -> None:
+ session_view = SessionView()
+ session_view.cell_notifications["1"] = _cell_notification(
+ cell_id="1",
+ mimetype="application/vnd.marimo+mimebundle",
+ data={
+ "application/vnd.vegalite.v6+json": {"mark": "point"},
+ "text/plain": "vega",
+ },
+ )
+ session_view.cell_ids = UpdateCellIdsNotification(cell_ids=["1"])
+ app = InternalApp(App())
+
+ class _FakeServer:
+ base_url = "http://127.0.0.1:1234"
+ page_url = "http://127.0.0.1:1234/__marimo_pdf_raster__.html"
+
+ def __enter__(self) -> Any:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ del args
+
+ def set_html(self, html: str) -> None:
+ assert "<html" in html
+
+ async def _capture_static(
+ *,
+ page_url: str,
+ targets: list[_pdf_raster._RasterTarget],
+ scale: float,
+ ) -> dict[str, str]:
+ assert page_url.endswith("__marimo_pdf_raster__.html")
+ assert scale == 4.0
+ assert [target.cell_id for target in targets] == ["1"]
+ return {"1": "data:image/png;base64,c3RhdGlj"}
+
+ live_capture_mock = AsyncMock(
+ side_effect=AssertionError(
+ "live capture should not run for static-only targets"
+ )
+ )
+
+ def _fake_export_as_html(*args: Any, **kwargs: Any) -> tuple[str, str]:
+ del args
+ del kwargs
+ return "<html></html>", "demo.html"
+
+ async def _run() -> dict[str, str]:
+ with (
+ patch.object(
+ _pdf_raster,
+ "HtmlAssetServer",
+ return_value=_FakeServer(),
+ ),
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_page",
+ side_effect=_capture_static,
+ ),
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_live_page",
+ live_capture_mock,
+ ),
+ patch(
+ "marimo._server.export.exporter.Exporter.export_as_html",
+ side_effect=_fake_export_as_html,
+ ),
+ ):
+ return await _pdf_raster.collect_pdf_png_fallbacks(
+ app=app,
+ session_view=session_view,
+ filename="demo.py",
+ filepath="demo.py",
+ options=_pdf_raster.PDFRasterizationOptions(),
+ )
+
+ captures = asyncio.run(_run())
+ assert captures == {"1": "data:image/png;base64,c3RhdGlj"}
+ live_capture_mock.assert_not_awaited()
+
+
+def test_collect_pdf_png_fallbacks_live_mode_uses_live_capture() -> None:
+ session_view = SessionView()
+ session_view.cell_notifications["1"] = _cell_notification(
+ cell_id="1",
+ mimetype="application/vnd.marimo+mimebundle",
+ data={
+ "application/vnd.vegalite.v6+json": {"mark": "point"},
+ "text/plain": "vega",
+ },
+ )
+ session_view.cell_notifications["2"] = _cell_notification(
+ cell_id="2",
+ mimetype="text/html",
+ data="<marimo-slider></marimo-slider>",
+ )
+ session_view.cell_ids = UpdateCellIdsNotification(cell_ids=["2", "1"])
+ app = InternalApp(App())
+
+ static_capture_mock = AsyncMock(
+ side_effect=AssertionError(
+ "static capture should not run for explicit live mode"
+ )
+ )
+
+ async def _capture_live(
+ *,
+ filepath: str,
+ targets: list[_pdf_raster._RasterTarget],
+ scale: float,
+ argv: list[str] | None,
+ ) -> dict[str, str]:
+ del filepath
+ del scale
+ del argv
+ assert [target.cell_id for target in targets] == ["2", "1"]
+ return {
+ "2": "data:image/png;base64,bGl2ZTI=",
+ "1": "data:image/png;base64,bGl2ZTE=",
+ }
+
+ async def _run() -> dict[str, str]:
+ with (
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_page",
+ static_capture_mock,
+ ),
+ patch.object(
+ _pdf_raster,
+ "_capture_pngs_from_live_page",
+ side_effect=_capture_live,
+ ),
+ ):
+ return await _pdf_raster.collect_pdf_png_fallbacks(
+ app=app,
+ session_view=session_view,
+ filename="demo.py",
+ filepath="demo.py",
+ options=_pdf_raster.PDFRasterizationOptions(
+ server_mode="live"
+ ),
+ )
+
+ captures = asyncio.run(_run())
+ assert captures == {
+ "1": "data:image/png;base64,bGl2ZTE=",
+ "2": "data:image/png;base64,bGl2ZTI=",
+ }
+ static_capture_mock.assert_not_awaited()
+
+
+def test_wait_for_target_ready_uses_settle_wait_for_dynamic_targets() -> None:
+ class _TimeoutError(Exception):
+ pass
+
+ page = AsyncMock()
+ locator = AsyncMock()
+ target = _pdf_raster._RasterTarget(
+ cell_id="dynamic-cell",
+ expects=("vega",),
+ )
+
+ settle_wait = AsyncMock()
+ with patch.object(
+ _pdf_raster,
+ "_wait_for_navigation_settled",
+ settle_wait,
+ ):
+ ready = asyncio.run(
+ _pdf_raster._wait_for_target_ready(
+ page=page,
+ target=target,
+ locator=locator,
+ timeout_error=_TimeoutError,
+ )
+ )
+
+ assert ready is True
+ settle_wait.assert_awaited_once()