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.

fix: preserve local images in HTML and PDF exports (#10938)

Péter Gyarmatib129be30fc1f
diff --git a/marimo/_convert/common/dom_traversal.py b/marimo/_convert/common/dom_traversal.py
index 2d114dbdb4..d9d2b02d52 100644
--- a/marimo/_convert/common/dom_traversal.py
+++ b/marimo/_convert/common/dom_traversal.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
import re
+from html import escape
from html.parser import HTMLParser
from typing import TYPE_CHECKING, cast
@@ -25,24 +26,11 @@ class _HTMLAttributeReplacer(HTMLParser):
This parser traverses HTML strings and applies a custom replacement function
to specified attributes in allowed tags.
- Example:
- ```python
- def upper_replacer(value: str) -> Optional[str]:
- return value.upper()
-
-
- replacer = HTMLAttributeReplacer(
- allowed_tags={"img"},
- allowed_attributes={"src"},
- replacer_fn=upper_replacer,
- )
- replacer.feed('<img src="test.png">')
- replacer.get_output()
- ```
"""
def __init__(
self,
+ html: str,
allowed_tags: set[str],
allowed_attributes: set[str],
replacer_fn: Callable[[str], str | None],
@@ -50,98 +38,58 @@ class _HTMLAttributeReplacer(HTMLParser):
"""Initialize the HTML attribute replacer.
Args:
+ html: The complete HTML source to preserve around replacements.
allowed_tags: Set of HTML tag names to process (e.g., {"img", "a"})
allowed_attributes: Set of attribute names to process (e.g., {"src", "href"})
replacer_fn: Function that takes an attribute value and returns
a replacement value, or None to keep the original
"""
- super().__init__()
+ super().__init__(convert_charrefs=False)
self.allowed_tags = {tag.lower() for tag in allowed_tags}
self.allowed_attributes = {attr.lower() for attr in allowed_attributes}
self.replacer_fn = replacer_fn
+ self._html = html
+ self._line_offsets = [0, *(m.end() for m in re.finditer("\n", html))]
+ self._last_offset = 0
self._output: list[str] = []
def handle_starttag(
self, tag: str, attrs: list[tuple[str, str | None]]
) -> None:
- """Handle opening tags, replacing attributes if applicable."""
- if tag.lower() in self.allowed_tags:
- # Process attributes for allowed tags
- new_attrs: list[tuple[str, str | None]] = []
- for attr_name, attr_value in attrs:
- if attr_name.lower() in self.allowed_attributes and attr_value:
- # Apply the replacer function
- replacement = self.replacer_fn(attr_value)
- new_attrs.append(
- (
- attr_name,
- replacement
- if replacement is not None
- else attr_value,
- )
- )
- else:
- new_attrs.append((attr_name, attr_value))
- attrs = new_attrs
-
- # Reconstruct the tag
- attrs_str = self._format_attrs(attrs)
- self._output.append(f"<{tag}{attrs_str}>")
-
- def handle_endtag(self, tag: str) -> None:
- """Handle closing tags."""
- self._output.append(f"</{tag}>")
-
- def handle_data(self, data: str) -> None:
- """Handle text content between tags."""
- self._output.append(data)
+ if tag not in self.allowed_tags:
+ return
+ new_attrs = []
+ for name, value in attrs:
+ replacement = (
+ self.replacer_fn(value)
+ if name in self.allowed_attributes and value
+ else None
+ )
+ new_attrs.append(
+ (name, replacement if replacement is not None else value)
+ )
+ if new_attrs == attrs:
+ return
+
+ # Splice only changed tags; rebuilding the rest would corrupt SVG,
+ # escaped code, and other content that HTMLParser normalizes or drops.
+ line, column = self.getpos()
+ start = self._line_offsets[line - 1] + column
+ original_tag = self.get_starttag_text()
+ assert original_tag is not None
+ ending = " />" if original_tag.endswith("/>") else ">"
+ self._output.extend(
+ (
+ self._html[self._last_offset : start],
+ f"<{tag}{self._format_attrs(new_attrs)}{ending}",
+ )
+ )
+ self._last_offset = start + len(original_tag)
def handle_startendtag(
self, tag: str, attrs: list[tuple[str, str | None]]
) -> None:
- """Handle self-closing tags (e.g., <img />)."""
- if tag.lower() in self.allowed_tags:
- # Process attributes for allowed tags
- new_attrs: list[tuple[str, str | None]] = []
- for attr_name, attr_value in attrs:
- if attr_name.lower() in self.allowed_attributes and attr_value:
- # Apply the replacer function
- replacement = self.replacer_fn(attr_value)
- new_attrs.append(
- (
- attr_name,
- replacement
- if replacement is not None
- else attr_value,
- )
- )
- else:
- new_attrs.append((attr_name, attr_value))
- attrs = new_attrs
-
- # Reconstruct the self-closing tag
- attrs_str = self._format_attrs(attrs)
- self._output.append(f"<{tag}{attrs_str} />")
-
- def handle_comment(self, data: str) -> None:
- """Preserve HTML comments."""
- self._output.append(f"<!--{data}-->")
-
- def handle_decl(self, decl: str) -> None:
- """Preserve declarations like DOCTYPE."""
- self._output.append(f"<!{decl}>")
-
- def handle_pi(self, data: str) -> None:
- """Preserve processing instructions."""
- self._output.append(f"<?{data}>")
-
- def handle_charref(self, name: str) -> None:
- """Preserve character references like &#123;."""
- self._output.append(f"&#{name};")
-
- def handle_entityref(self, name: str) -> None:
- """Preserve entity references like &nbsp;."""
- self._output.append(f"&{name};")
+ self.handle_starttag(tag, attrs)
def _format_attrs(self, attrs: list[tuple[str, str | None]]) -> str:
"""Format attributes for output."""
@@ -154,13 +102,13 @@ class _HTMLAttributeReplacer(HTMLParser):
formatted.append(name)
else:
# Escape quotes in the value
- escaped_value = value.replace('"', "&quot;")
+ escaped_value = escape(value, quote=True)
formatted.append(f'{name}="{escaped_value}"')
return " " + " ".join(formatted)
def get_output(self) -> str:
"""Get the processed HTML output."""
- return "".join(self._output)
+ return "".join(self._output) + self._html[self._last_offset :]
def replace_html_attributes(
@@ -200,6 +148,7 @@ def replace_html_attributes(
```
"""
parser = _HTMLAttributeReplacer(
+ html=html,
allowed_tags=allowed_tags,
allowed_attributes=allowed_attributes,
replacer_fn=replacer_fn,
diff --git a/marimo/_export/_limits.py b/marimo/_export/_limits.py
new file mode 100644
index 0000000000..968bd811a9
--- /dev/null
+++ b/marimo/_export/_limits.py
@@ -0,0 +1,5 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+# Maximum asset size to inline in HTML, including HTML rendered for PDFs.
+MAX_VIRTUAL_FILE_INLINE_BYTES = 10 * 1024 * 1024
diff --git a/marimo/_export/_nbconvert.py b/marimo/_export/_nbconvert.py
new file mode 100644
index 0000000000..06fc79a127
--- /dev/null
+++ b/marimo/_export/_nbconvert.py
@@ -0,0 +1,127 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from marimo._convert.common.dom_traversal import (
+ replace_public_files_with_data_uris,
+ replace_virtual_files_with_data_uris,
+)
+from marimo._convert.ipynb.from_ir import NBCONVERT_REMOVE_INPUT_TAG
+from marimo._export._limits import MAX_VIRTUAL_FILE_INLINE_BYTES
+
+if TYPE_CHECKING:
+ from traitlets.config import Config
+
+
+def inline_pdf_assets(html: str, filename: str | None) -> str:
+ """Resolve notebook assets before Chromium opens HTML in a temp directory."""
+ html, _ = replace_virtual_files_with_data_uris(
+ html,
+ allowed_tags={"img", "audio", "video", "source"},
+ allowed_attributes={"src"},
+ max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
+ )
+ if filename is not None:
+ html, _ = replace_public_files_with_data_uris(
+ html,
+ public_dir=Path(filename).resolve().parent / "public",
+ max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
+ )
+ return html
+
+
+def _nbconvert_tag_remove_config() -> Config:
+ """Build a traitlets config that strips inputs from cells tagged with
+ `NBCONVERT_REMOVE_INPUT_TAG`. Used to honor `hide_code=True` in nbconvert
+ exports."""
+ from traitlets.config import Config
+
+ config = Config()
+ config.TagRemovePreprocessor.enabled = True
+ config.TagRemovePreprocessor.remove_input_tags = (
+ NBCONVERT_REMOVE_INPUT_TAG,
+ )
+ return config
+
+
+# JupyterLab's stylesheet (shipped with nbconvert) styles the code input area
+# with `overflow: hidden` and leaves the `<pre>` at the default `white-space:
+# pre`. In JupyterLab that is fine because the editor scrolls; in a PDF there is
+# no scrolling, so long lines are clipped and the text is lost entirely.
+# Outputs already wrap (`.jp-OutputArea-output pre` sets `word-break`), so this
+# only targets the input area.
+#
+# `!important` is required because this is inlined ahead of the JupyterLab
+# rules; the slides PDF path overrides nbconvert styling the same way.
+WEBPDF_CODE_WRAP_CSS = """\
+/* marimo: wrap long code lines instead of clipping them (#9421) */
+.jp-InputArea-editor {
+ overflow: visible !important;
+}
+.jp-InputArea-editor .highlight pre {
+ white-space: pre-wrap !important;
+ overflow-wrap: anywhere !important;
+}
+"""
+
+
+def _inline_code_wrap_css(nb: Any, resources: Any) -> tuple[Any, Any]:
+ """Inline `WEBPDF_CODE_WRAP_CSS`, as an nbconvert preprocessor.
+
+ Preprocessors run after nbconvert populates `resources`, so appending here
+ is what gets the stylesheet into the rendered HTML.
+ """
+ inlining = resources.setdefault("inlining", {})
+ inlining.setdefault("css", []).append(WEBPDF_CODE_WRAP_CSS)
+ return nb, resources
+
+
+def _render_webpdf_html(
+ notebook: Any, include_inputs: bool, filename: str | None
+) -> str:
+ from nbconvert import HTMLExporter # type: ignore[import-not-found]
+
+ html_exporter = HTMLExporter( # type: ignore[no-untyped-call]
+ template_name="webpdf",
+ config=_nbconvert_tag_remove_config(),
+ )
+ html_exporter.exclude_input = not include_inputs
+ html_exporter.register_preprocessor( # type: ignore[no-untyped-call]
+ _inline_code_wrap_css, enabled=True
+ )
+ html, _resources = html_exporter.from_notebook_node(notebook) # type: ignore[no-untyped-call]
+ return inline_pdf_assets(html, filename)
+
+
+def _print_webpdf(html: str) -> Any:
+ if sys.platform == "win32":
+ # marimo installs the Selector policy during import. The spawned render
+ # process restores Proactor before Playwright creates its subprocess loop.
+ asyncio.set_event_loop_policy(None)
+
+ from nbconvert import WebPDFExporter # type: ignore[import-not-found]
+
+ exporter = WebPDFExporter(allow_chromium_download=True) # type: ignore[no-untyped-call]
+ return exporter.run_playwright(html) # type: ignore[no-untyped-call]
+
+
+def _render_webpdf(
+ notebook: Any, include_inputs: bool, filename: str | None = None
+) -> Any:
+ # Resolve process-local virtual files before crossing the spawn boundary.
+ html = _render_webpdf_html(notebook, include_inputs, filename)
+ if sys.platform != "win32":
+ return _print_webpdf(html)
+
+ from concurrent.futures import ProcessPoolExecutor
+ from multiprocessing import get_context
+
+ with ProcessPoolExecutor(
+ max_workers=1,
+ mp_context=get_context("spawn"),
+ ) as pool:
+ return pool.submit(_print_webpdf, html).result()
diff --git a/marimo/_export/exporter.py b/marimo/_export/exporter.py
index 773090e6b8..d46681a0ff 100644
--- a/marimo/_export/exporter.py
+++ b/marimo/_export/exporter.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import base64
-import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, cast
@@ -28,7 +27,6 @@ from marimo._convert.common.filename import (
)
from marimo._convert.converters import MarimoConvert
from marimo._convert.ipynb.from_ir import (
- NBCONVERT_REMOVE_INPUT_TAG,
convert_from_ir_to_ipynb,
)
from marimo._convert.markdown.flavor import (
@@ -36,6 +34,12 @@ from marimo._convert.markdown.flavor import (
normalize_markdown_flavor,
)
from marimo._convert.script import convert_from_ir_to_script
+from marimo._export._limits import MAX_VIRTUAL_FILE_INLINE_BYTES
+from marimo._export._nbconvert import (
+ _nbconvert_tag_remove_config,
+ _render_webpdf,
+ inline_pdf_assets,
+)
from marimo._export._status import emit_pdf_export_status
from marimo._export.dependencies import require_export_dependencies
from marimo._export.requests import (
@@ -69,8 +73,6 @@ from marimo._version import __version__
if TYPE_CHECKING:
from collections.abc import Iterator
- from traitlets.config import Config
-
LOGGER = _loggers.marimo_logger()
# Root directory for static assets
@@ -78,94 +80,6 @@ ROOT = (marimo_package_path() / "_static").resolve()
VIRTUAL_FILE_ALLOWED_ATTRIBUTES = {"src"}
VIRTUAL_FILE_ALLOWED_TAGS = {"img", "audio", "video"}
-# Maximum file size to inline as a data URI in exported HTML (10 MB).
-# Files exceeding this limit are replaced with a text/plain placeholder
-# so users see a clear message instead of a broken link.
-MAX_VIRTUAL_FILE_INLINE_BYTES = 10 * 1024 * 1024
-
-
-def _nbconvert_tag_remove_config() -> Config:
- """Build a traitlets config that strips inputs from cells tagged with
- `NBCONVERT_REMOVE_INPUT_TAG`. Used to honor `hide_code=True` in nbconvert
- exports."""
- from traitlets.config import Config
-
- config = Config()
- config.TagRemovePreprocessor.enabled = True
- config.TagRemovePreprocessor.remove_input_tags = (
- NBCONVERT_REMOVE_INPUT_TAG,
- )
- return config
-
-
-# JupyterLab's stylesheet (shipped with nbconvert) styles the code input area
-# with `overflow: hidden` and leaves the `<pre>` at the default `white-space:
-# pre`. In JupyterLab that is fine because the editor scrolls; in a PDF there is
-# no scrolling, so long lines are clipped and the text is lost entirely.
-# Outputs already wrap (`.jp-OutputArea-output pre` sets `word-break`), so this
-# only targets the input area.
-#
-# `!important` is required because this is inlined ahead of the JupyterLab
-# rules; the slides PDF path overrides nbconvert styling the same way.
-WEBPDF_CODE_WRAP_CSS = """\
-/* marimo: wrap long code lines instead of clipping them (#9421) */
-.jp-InputArea-editor {
- overflow: visible !important;
-}
-.jp-InputArea-editor .highlight pre {
- white-space: pre-wrap !important;
- overflow-wrap: anywhere !important;
-}
-"""
-
-
-def _inline_code_wrap_css(nb: Any, resources: Any) -> tuple[Any, Any]:
- """Inline `WEBPDF_CODE_WRAP_CSS`, as an nbconvert preprocessor.
-
- Preprocessors run after nbconvert populates `resources`, so appending here
- is what gets the stylesheet into the rendered HTML.
- """
- inlining = resources.setdefault("inlining", {})
- inlining.setdefault("css", []).append(WEBPDF_CODE_WRAP_CSS)
- return nb, resources
-
-
-def _render_webpdf_with_nbconvert(notebook: Any, include_inputs: bool) -> Any:
- if sys.platform == "win32":
- # marimo installs the Selector policy during import. The spawned render
- # process restores Proactor before Playwright creates its subprocess loop.
- asyncio.set_event_loop_policy(None)
-
- from nbconvert import WebPDFExporter # type: ignore[import-not-found]
-
- web_exporter = WebPDFExporter( # type: ignore[no-untyped-call]
- config=_nbconvert_tag_remove_config(),
- )
- web_exporter.exclude_input = not include_inputs
- web_exporter.allow_chromium_download = True
- web_exporter.register_preprocessor( # type: ignore[no-untyped-call]
- _inline_code_wrap_css, enabled=True
- )
- pdf_data, _resources = web_exporter.from_notebook_node(notebook) # type: ignore[no-untyped-call]
- return pdf_data
-
-
-def _render_webpdf(notebook: Any, include_inputs: bool) -> Any:
- if sys.platform != "win32":
- return _render_webpdf_with_nbconvert(notebook, include_inputs)
-
- from concurrent.futures import ProcessPoolExecutor
- from multiprocessing import get_context
-
- with ProcessPoolExecutor(
- max_workers=1,
- mp_context=get_context("spawn"),
- ) as pool:
- return pool.submit(
- _render_webpdf_with_nbconvert,
- notebook,
- include_inputs,
- ).result()
def export_script(request: ScriptExportRequest) -> ExportResult:
@@ -295,10 +209,10 @@ class Exporter:
def _iter_html_data_strings(
session_snapshot: NotebookSessionV1,
) -> Iterator[tuple[dict[str, Any], str, str]]:
- """Yield (output_data_dict, mime_type, data) for each `text/html`
- string output.
+ """Yield (output_data_dict, mime_type, data) for rendered HTML outputs.
- Only `text/html` outputs are returned: non-HTML mime entries (e.g.
+ `mo.md` emits rendered HTML with a `text/markdown` MIME type.
+ Only these HTML-bearing outputs are returned: non-HTML mime entries (e.g.
`text/plain`, `application/json`) must not be HTML-parsed, since
their content is opaque to the attribute-replacement logic.
"""
@@ -307,7 +221,7 @@ class Exporter:
if output["type"] != "data":
continue
for mime_type, data in output["data"].items():
- if mime_type != "text/html":
+ if mime_type not in {"text/html", "text/markdown"}:
continue
if isinstance(data, str):
yield output["data"], mime_type, data
@@ -652,7 +566,9 @@ class Exporter:
phase="render",
message="rendering PDF via WebPDF...",
)
- pdf_data = _render_webpdf(notebook, request.options.include_inputs)
+ pdf_data = _render_webpdf(
+ notebook, request.options.include_inputs, request.app.filename
+ )
if not isinstance(pdf_data, bytes):
LOGGER.error("PDF data is not bytes: %s", pdf_data)
@@ -706,7 +622,7 @@ class Exporter:
message="rendering slides PDF...",
)
return await self._export_slides_as_pdf(
- notebook, request.options.include_inputs
+ notebook, request.options.include_inputs, request.app.filename
)
@staticmethod
@@ -732,6 +648,7 @@ class Exporter:
async def _export_slides_as_pdf(
notebook: Any,
include_inputs: bool,
+ filename: str | None = None,
) -> bytes | None:
"""Render slides notebook to PDF using Playwright async API."""
import os
@@ -754,6 +671,8 @@ class Exporter:
slides_exporter.exclude_input = not include_inputs
html_data, _resources = slides_exporter.from_notebook_node(notebook)
+ html_data = inline_pdf_assets(html_data, filename)
+
# Write HTML to a temp file for Playwright to load
with tempfile.NamedTemporaryFile(
suffix=".html", delete=False, mode="w", encoding="utf-8"
diff --git a/tests/_convert/common/test_dom_traversal.py b/tests/_convert/common/test_dom_traversal.py
index ad1c500e54..fc0e2aab87 100644
--- a/tests/_convert/common/test_dom_traversal.py
+++ b/tests/_convert/common/test_dom_traversal.py
@@ -18,6 +18,34 @@ from marimo._convert.common.dom_traversal import (
class TestHTMLAttributeReplacer:
+ def test_preserves_source_around_replaced_tags(self) -> None:
+ html = (
+ '<!DOCTYPE html>\r\n<svg viewBox="0 0 20 20">'
+ "<text><![CDATA[A < B & C]]></text></svg>\n"
+ '<pre>&lt;img src="public/image.png"&gt; &amp; &#39;</pre>\n'
+ '<script>const s = "<img src=public/image.png>";</script>'
+ '<img src="public/image.png" alt="&amp;quot;" />\n'
+ '<IMG SRC="https://example.com/image.png">'
+ '<img\nsrc="public/image.png">'
+ )
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=lambda value: (
+ "data:image/png;base64,PNG"
+ if value == "public/image.png"
+ else None
+ ),
+ )
+ assert result == html.replace(
+ '<img src="public/image.png" alt="&amp;quot;" />',
+ '<img src="data:image/png;base64,PNG" alt="&amp;quot;" />',
+ ).replace(
+ '<img\nsrc="public/image.png">',
+ '<img src="data:image/png;base64,PNG">',
+ )
+
def test_simple_replacement(self) -> None:
"""Test basic attribute replacement."""
html = '<img src="test.png">'
diff --git a/tests/_export/test_export_images.py b/tests/_export/test_export_images.py
new file mode 100644
index 0000000000..24f1077feb
--- /dev/null
+++ b/tests/_export/test_export_images.py
@@ -0,0 +1,206 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+from typing import TYPE_CHECKING
+from unittest.mock import patch
+
+import pytest
+
+from marimo._export._limits import MAX_VIRTUAL_FILE_INLINE_BYTES
+from marimo._export._nbconvert import inline_pdf_assets
+from marimo._export.file import export_html, export_pdf
+from marimo._export.requests import (
+ HTMLFileExportRequest,
+ NotebookExecutionOptions,
+ PDFFileExportRequest,
+)
+from marimo._schemas.export_options import HTMLExportOptions, PDFExportOptions
+from marimo._utils.marimo_path import MarimoPath
+from tests._server.templates.utils import parse_mount_config
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+def test_pdf_assets_skip_oversized_files_without_reading(
+ tmp_path: Path,
+) -> None:
+ public = tmp_path / "public"
+ public.mkdir()
+ size = MAX_VIRTUAL_FILE_INLINE_BYTES + 1
+ with (public / "large.png").open("wb") as image:
+ image.truncate(size)
+ html = (
+ '<img src="public/large.png">'
+ f'<video src="./@file/{size}-large.mp4"></video>'
+ )
+ with (
+ patch("pathlib.Path.read_bytes") as read_public,
+ patch(
+ "marimo._convert.common.dom_traversal.read_virtual_file"
+ ) as read_virtual,
+ ):
+ result = inline_pdf_assets(html, str(tmp_path / "notebook.py"))
+
+ read_public.assert_not_called()
+ read_virtual.assert_not_called()
+ message = (
+ f"File too large to inline ({size} bytes, "
+ f"limit {MAX_VIRTUAL_FILE_INLINE_BYTES})"
+ )
+ encoded = base64.b64encode(message.encode()).decode()
+ assert result == (
+ '<img src="public/large.png">'
+ f'<video src="data:text/plain;base64,{encoded}"></video>'
+ )
+
+
+def image_notebook(tmp_path: Path) -> Path:
+ public = tmp_path / "public"
+ public.mkdir()
+ (public / "image.svg").write_text(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">'
+ '<rect width="20" height="20" fill="blue"/></svg>'
+ )
+ notebook = tmp_path / "images.py"
+ notebook.write_text("""import marimo
+app = marimo.App()
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+def _(mo):
+ mo.md("![markdown](public/image.svg)")
+ return
+
+def _(mo):
+ mo.image("./public/image.svg", alt="standalone")
+ return
+
+def _(mo):
+ mo.vstack([mo.image("public/image.svg", alt="stacked")])
+ return
+
+def _(mo):
+ _name = "dynamic"
+ mo.md(f"![{_name}](public/image.svg)")
+ return
+""")
+ return notebook
+
+
+async def test_html_export_inlines_rendered_markdown_images(
+ image_notebook: Path,
+) -> None:
+ result = await export_html(
+ HTMLFileExportRequest(
+ path=MarimoPath(image_notebook),
+ options=HTMLExportOptions(files=(), include_code=True),
+ execution=NotebookExecutionOptions(cli_args={}, argv=None),
+ )
+ )
+ assert not result.did_error
+ cells = parse_mount_config(result.text)["session"]["cells"]
+ outputs = [cell["outputs"][0]["data"] for cell in cells[1:]]
+ encoded = base64.b64encode(
+ (image_notebook.parent / "public" / "image.svg").read_bytes()
+ ).decode()
+ for output in outputs:
+ html = next(iter(output.values()))
+ assert f"data:image/svg+xml;base64,{encoded}" in html
+ assert "public/image.svg" not in html
+
+
[email protected]("nbformat", "nbconvert")
[email protected]("include_outputs", [True, False])
+async def test_webpdf_inlines_images_relative_to_notebook(
+ image_notebook: Path, include_outputs: bool
+) -> None:
+ from bs4 import BeautifulSoup
+ from nbconvert import WebPDFExporter
+
+ with (
+ patch("marimo._export.exporter.require_export_dependencies"),
+ patch("marimo._export._nbconvert.sys", platform="linux"),
+ patch.object(
+ WebPDFExporter, "run_playwright", return_value=b"pdf"
+ ) as print_pdf,
+ ):
+ result = await export_pdf(
+ PDFFileExportRequest(
+ path=MarimoPath(image_notebook),
+ options=PDFExportOptions(
+ preset="document", include_inputs=False, webpdf=True
+ ),
+ execution=(
+ NotebookExecutionOptions(cli_args={}, argv=None)
+ if include_outputs
+ else None
+ ),
+ )
+ )
+
+ assert result is not None
+ assert not result.did_error
+ html = BeautifulSoup(print_pdf.call_args.args[0], "html.parser")
+ images = html.find_all("img")
+ assert [image["alt"] for image in images] == (
+ ["markdown", "standalone", "stacked", "dynamic"]
+ if include_outputs
+ else ["markdown"]
+ )
+ expected = (image_notebook.parent / "public" / "image.svg").read_bytes()
+ for image in images:
+ prefix, encoded = image["src"].split(",", 1)
+ assert prefix == "data:image/svg+xml;base64"
+ assert base64.b64decode(encoded) == expected
+
+
[email protected]("nbformat", "nbconvert")
+def test_webpdf_resolves_virtual_images_before_spawning(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import nbformat
+
+ from marimo._export._nbconvert import _render_webpdf
+ from marimo._runtime.virtual_file import (
+ InMemoryStorage,
+ VirtualFileStorageManager,
+ )
+
+ # Import optional dependencies before simulating the Windows branch.
+ pytest.importorskip("nbconvert")
+ storage = InMemoryStorage()
+ storage.store("image.svg", b"<svg/>")
+ monkeypatch.setattr(VirtualFileStorageManager(), "storage", storage)
+ notebook = nbformat.v4.new_notebook(
+ cells=[
+ nbformat.v4.new_code_cell(
+ outputs=[
+ nbformat.v4.new_output(
+ "display_data",
+ data={"text/html": '<img src="./@file/6-image.svg">'},
+ )
+ ]
+ )
+ ]
+ )
+ with (
+ patch("marimo._export._nbconvert.sys", platform="win32"),
+ patch("concurrent.futures.ProcessPoolExecutor") as pool,
+ ):
+ worker = pool.return_value.__enter__.return_value
+ worker.submit.return_value.result.return_value = b"pdf"
+ assert _render_webpdf(notebook, include_inputs=False) == b"pdf"
+
+ html = worker.submit.call_args.args[1]
+ assert 'src="data:image/svg+xml;base64,PHN2Zy8+"' in html
+ assert "./@file/" not in html
diff --git a/tests/_export/test_exporter.py b/tests/_export/test_exporter.py
index 5f8be44286..3a3b44e9a4 100644
--- a/tests/_export/test_exporter.py
+++ b/tests/_export/test_exporter.py
@@ -1414,14 +1414,14 @@ def test_export_html_inlines_public_folder_images(
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- # Simulate the HTML output that mo.md produces at runtime: the raw
+ # mo.md emits rendered HTML under text/markdown: the raw
# `public/image.png` path is preserved (no inlining at runtime).
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
- mimetype="text/html",
+ mimetype="text/markdown",
data=(
'<span class="markdown">'
'<img alt="alt" src="public/image.png">'
@@ -1938,10 +1938,9 @@ class TestPDFExport:
Regression test for marimo-team/marimo#9421.
"""
import nbformat
- from nbconvert import WebPDFExporter
- from marimo._export.exporter import (
- _render_webpdf_with_nbconvert,
+ from marimo._export._nbconvert import (
+ _render_webpdf_html,
)
notebook = nbformat.v4.new_notebook()
@@ -1952,31 +1951,9 @@ class TestPDFExport:
)
]
- # `run_playwright` receives the fully rendered HTML, so stubbing it
- # captures what Chromium would have been handed without needing a
- # browser. Going through `_render_webpdf_with_nbconvert` means the
- # test fails if the production code stops registering the
- # preprocessor.
- rendered: list[str] = []
-
- def fake_run_playwright(self: Any, html: str) -> bytes:
- del self
- rendered.append(html)
- return b"mock_pdf_data"
-
- with patch.object(
- WebPDFExporter, "run_playwright", fake_run_playwright
- ):
- pdf_data = _render_webpdf_with_nbconvert(
- notebook, include_inputs=True
- )
-
- assert pdf_data == b"mock_pdf_data"
- assert len(rendered) == 1
- # Assert on the distinctive selector and properties rather than the
- # whole CSS constant, so the test is not brittle to nbconvert
- # whitespace/comment handling when inlining the stylesheet.
- html = rendered[0]
+ html = _render_webpdf_html(
+ notebook, include_inputs=True, filename=None
+ )
assert ".jp-InputArea-editor .highlight pre" in html
assert "white-space: pre-wrap !important" in html
assert "overflow-wrap: anywhere !important" in html
@@ -2086,6 +2063,7 @@ class TestPDFExport:
session_view: SessionView,
) -> None:
"""Test PDF export in webpdf mode (mocked)."""
+ from bs4 import BeautifulSoup
app = App()
@@ -2097,9 +2075,8 @@ class TestPDFExport:
exporter = Exporter()
mock_exporter_instance = MagicMock()
- mock_exporter_instance.from_notebook_node.return_value = (
- b"mock_webpdf_data",
- {},
+ mock_exporter_instance.run_playwright.return_value = (
+ b"mock_webpdf_data"
)
with (
@@ -2118,9 +2095,14 @@ class TestPDFExport:
)
assert result == b"mock_webpdf_data"
- mock_webpdf_exporter.assert_called_once()
- assert mock_exporter_instance.exclude_input is False
- assert mock_exporter_instance.allow_chromium_download is True
+ mock_webpdf_exporter.assert_called_once_with(
+ allow_chromium_download=True
+ )
+ html = BeautifulSoup(
+ mock_exporter_instance.run_playwright.call_args.args[0],
+ "html.parser",
+ )
+ assert html.select_one(".jp-InputArea") is not None
@pytest.mark.skipif(
sys.platform != "win32" or not DependencyManager.nbformat.has(),
@@ -2131,13 +2113,13 @@ class TestPDFExport:
) -> None:
import nbformat
- from marimo._export.exporter import _render_webpdf
+ from marimo._export._nbconvert import _render_webpdf
(tmp_path / "nbconvert.py").write_text(
textwrap.dedent(
"""
- class WebPDFExporter:
- def __init__(self, config):
+ class HTMLExporter:
+ def __init__(self, config, template_name):
self.config = config
self.preprocessors = []
@@ -2145,7 +2127,14 @@ class TestPDFExport:
self.preprocessors.append((preprocessor, enabled))
def from_notebook_node(self, notebook):
- return b"mock_webpdf_data", {}
+ return "<html></html>", {}
+
+ class WebPDFExporter:
+ def __init__(self, allow_chromium_download):
+ pass
+
+ def run_playwright(self, html):
+ return b"mock_webpdf_data"
"""
),
encoding="utf-8",
@@ -2169,8 +2158,8 @@ class TestPDFExport:
reason="requires Windows and nbconvert",
)
def test_webpdf_worker_can_spawn_subprocess_on_windows(self) -> None:
- from marimo._export.exporter import (
- _render_webpdf_with_nbconvert,
+ from marimo._export._nbconvert import (
+ _print_webpdf,
)
async def spawn_process() -> None:
@@ -2181,14 +2170,12 @@ class TestPDFExport:
mock_exporter_instance = MagicMock()
- def render(
- *_args: Any, **_kwargs: Any
- ) -> tuple[bytes, dict[Any, Any]]:
+ def render(*_args: Any, **_kwargs: Any) -> bytes:
with ThreadPoolExecutor(max_workers=1) as pool:
pool.submit(asyncio.run, spawn_process()).result()
- return b"mock_webpdf_data", {}
+ return b"mock_webpdf_data"
- mock_exporter_instance.from_notebook_node.side_effect = render
+ mock_exporter_instance.run_playwright.side_effect = render
original_policy = asyncio.get_event_loop_policy()
selector_policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(selector_policy)
@@ -2198,9 +2185,7 @@ class TestPDFExport:
"nbconvert.WebPDFExporter", create=True
) as mock_webpdf_exporter:
mock_webpdf_exporter.return_value = mock_exporter_instance
- result = _render_webpdf_with_nbconvert(
- MagicMock(), include_inputs=True
- )
+ result = _print_webpdf("<html></html>")
assert result == b"mock_webpdf_data"
finally:
@@ -2216,6 +2201,7 @@ class TestPDFExport:
session_view: SessionView,
) -> None:
"""Test WebPDF export suppressing code inputs."""
+ from bs4 import BeautifulSoup
app = App()
@@ -2227,9 +2213,8 @@ class TestPDFExport:
exporter = Exporter()
mock_exporter_instance = MagicMock()
- mock_exporter_instance.from_notebook_node.return_value = (
- b"mock_webpdf_data_no_inputs",
- {},
+ mock_exporter_instance.run_playwright.return_value = (
+ b"mock_webpdf_data_no_inputs"
)
with (
@@ -2249,9 +2234,14 @@ class TestPDFExport:
)
assert result == b"mock_webpdf_data_no_inputs"
- mock_webpdf_exporter.assert_called_once()
- assert mock_exporter_instance.exclude_input is True
- assert mock_exporter_instance.allow_chromium_download is True
+ mock_webpdf_exporter.assert_called_once_with(
+ allow_chromium_download=True
+ )
+ html = BeautifulSoup(
+ mock_exporter_instance.run_playwright.call_args.args[0],
+ "html.parser",
+ )
+ assert html.select_one(".jp-InputArea") is None
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
@@ -2324,9 +2314,8 @@ class TestPDFExport:
# Mock WebPDFExporter to succeed
mock_webpdf_exporter_instance = MagicMock()
- mock_webpdf_exporter_instance.from_notebook_node.return_value = (
- b"fallback_webpdf_data",
- {},
+ mock_webpdf_exporter_instance.run_playwright.return_value = (
+ b"fallback_webpdf_data"
)
with (
@@ -2354,13 +2343,10 @@ class TestPDFExport:
mock_pdf_exporter_instance.from_notebook_node.assert_called_once()
assert mock_pdf_exporter_instance.exclude_input is True
# WebPDFExporter was used as fallback
- mock_webpdf_exporter.assert_called_once()
- mock_webpdf_exporter_instance.from_notebook_node.assert_called_once()
- assert mock_webpdf_exporter_instance.exclude_input is True
- # Verify allow_chromium_download is set on fallback
- assert (
- mock_webpdf_exporter_instance.allow_chromium_download is True
+ mock_webpdf_exporter.assert_called_once_with(
+ allow_chromium_download=True
)
+ mock_webpdf_exporter_instance.run_playwright.assert_called_once()
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
@@ -2391,9 +2377,8 @@ class TestPDFExport:
)
mock_webpdf_exporter_instance = MagicMock()
- mock_webpdf_exporter_instance.from_notebook_node.return_value = (
- b"fallback_webpdf_data",
- {},
+ mock_webpdf_exporter_instance.run_playwright.return_value = (
+ b"fallback_webpdf_data"
)
with (
@@ -2416,8 +2401,10 @@ class TestPDFExport:
assert result == b"fallback_webpdf_data"
mock_pdf_exporter.assert_called_once()
mock_pdf_exporter_instance.from_notebook_node.assert_called_once()
- mock_webpdf_exporter.assert_called_once()
- mock_webpdf_exporter_instance.from_notebook_node.assert_called_once()
+ mock_webpdf_exporter.assert_called_once_with(
+ allow_chromium_download=True
+ )
+ mock_webpdf_exporter_instance.run_playwright.assert_called_once()
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
@@ -2445,9 +2432,8 @@ class TestPDFExport:
)
mock_webpdf_exporter_instance = MagicMock()
- mock_webpdf_exporter_instance.from_notebook_node.return_value = (
- b"fallback_webpdf_data",
- {},
+ mock_webpdf_exporter_instance.run_playwright.return_value = (
+ b"fallback_webpdf_data"
)
with (
@@ -2469,7 +2455,9 @@ class TestPDFExport:
assert result == b"fallback_webpdf_data"
mock_pdf_exporter.assert_called_once()
- mock_webpdf_exporter.assert_called_once()
+ mock_webpdf_exporter.assert_called_once_with(
+ allow_chromium_download=True
+ )
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
@@ -2496,9 +2484,8 @@ class TestPDFExport:
)
mock_webpdf_exporter_instance = MagicMock()
- mock_webpdf_exporter_instance.from_notebook_node.return_value = (
- b"fallback_webpdf_data",
- {},
+ mock_webpdf_exporter_instance.run_playwright.return_value = (
+ b"fallback_webpdf_data"
)
with (