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: add PDF with initial page number (#66)

Myles Scolnick7c31330d8c5b
diff --git a/docs/api/media/audio.md b/docs/api/media/audio.md
index 390b722141..3b7f8ddf37 100644
--- a/docs/api/media/audio.md
+++ b/docs/api/media/audio.md
@@ -2,7 +2,7 @@
<!-- TODO: add interactive marimo.audio doc.
At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
-<!-- <iframe class="demo" src="https://components.marimo.io/?component=refresh" frameborder="no"></iframe> -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=audio" frameborder="no"></iframe> -->
```{eval-rst}
.. autofunction:: marimo.audio
diff --git a/docs/api/media/image.md b/docs/api/media/image.md
index eec7181f98..31f079d90e 100644
--- a/docs/api/media/image.md
+++ b/docs/api/media/image.md
@@ -2,7 +2,7 @@
<!-- TODO: add interactive marimo.image doc.
At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
-<!-- <iframe class="demo" src="https://components.marimo.io/?component=refresh" frameborder="no"></iframe> -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=image" frameborder="no"></iframe> -->
```{eval-rst}
.. autofunction:: marimo.image
diff --git a/docs/api/media/index.md b/docs/api/media/index.md
index d45172a47f..9bfb8d4ea9 100644
--- a/docs/api/media/index.md
+++ b/docs/api/media/index.md
@@ -1,6 +1,6 @@
# Media
-Use `mo.image` and `mo.audio` to embed images and audio in your outputs.
+Use `mo.image`, `mo.audio`, and `mo.pdf` to embed media in your outputs.
```{eval-rst}
.. autosummary::
@@ -8,4 +8,5 @@ Use `mo.image` and `mo.audio` to embed images and audio in your outputs.
marimo.image
marimo.audio
+ marimo.pdf
```
diff --git a/docs/api/media/pdf.md b/docs/api/media/pdf.md
new file mode 100644
index 0000000000..225420dceb
--- /dev/null
+++ b/docs/api/media/pdf.md
@@ -0,0 +1,9 @@
+# PDF
+
+<!-- TODO: add interactive marimo.pdf doc.
+At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=pdf" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autofunction:: marimo.pdf
+```
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 30a95f1cc9..6ac6e77e26 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -28,6 +28,7 @@ __all__ = [
"image",
"left",
"md",
+ "pdf",
"refs",
"right",
"stop",
@@ -51,6 +52,7 @@ from marimo._plugins.stateless.audio import audio
from marimo._plugins.stateless.callout_output import callout
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.image import image
+from marimo._plugins.stateless.pdf import pdf
from marimo._plugins.stateless.tabs import tabs
from marimo._plugins.stateless.tree import tree
from marimo._runtime.control_flow import MarimoStopError, stop
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
index 045ed5c911..d590f5493b 100644
--- a/marimo/_output/builder.py
+++ b/marimo/_output/builder.py
@@ -57,6 +57,28 @@ class _HTMLBuilder:
else:
return f"<audio {_join_params(params)} />"
+ @staticmethod
+ def iframe(
+ src: Optional[str] = None,
+ width: Optional[str] = None,
+ height: Optional[str] = None,
+ style: Optional[str] = None,
+ ) -> str:
+ params: List[Tuple[str, str]] = []
+ if src:
+ params.append(("src", src))
+ if width:
+ params.append(("width", width))
+ if height:
+ params.append(("height", height))
+ if style:
+ params.append(("style", style))
+
+ if len(params) == 0:
+ return "<iframe />"
+ else:
+ return f"<iframe {_join_params(params)} />"
+
def _join_params(params: List[Tuple[str, str]]) -> str:
return " ".join([f"{k}='{v}'" if v != "" else f"{k}" for k, v in params])
diff --git a/marimo/_output/test_builder.py b/marimo/_output/test_builder.py
index 8e7a4d1b18..fed14473c2 100644
--- a/marimo/_output/test_builder.py
+++ b/marimo/_output/test_builder.py
@@ -23,6 +23,14 @@ def test_audio() -> None:
)
+def test_iframe() -> None:
+ assert h.iframe() == "<iframe />"
+ assert (
+ h.iframe(src="https://marimo.io")
+ == "<iframe src='https://marimo.io' />"
+ )
+
+
def test_join_params() -> None:
assert (
_join_params([("style", "color:red"), ("class", "myClass")])
diff --git a/marimo/_plugins/stateless/pdf.py b/marimo/_plugins/stateless/pdf.py
new file mode 100644
index 0000000000..0d89b0bb56
--- /dev/null
+++ b/marimo/_plugins/stateless/pdf.py
@@ -0,0 +1,76 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import io
+from typing import Any, Optional, Union
+
+from marimo._output.builder import h
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._output.utils import create_style
+
+
+@mddoc
+def pdf(
+ src: Union[str, io.IOBase],
+ initial_page: Optional[int] = None,
+ width: Optional[Union[int, str]] = "100%",
+ height: Optional[Union[int, str]] = "70vh", # arbitrary, but good default
+ style: Optional[dict[str, Any]] = None,
+) -> Html:
+ """Render a PDF.
+
+ This currently uses the native browser PDF viewer,
+ but may be replaced with a custom viewer.
+
+ **Example.**
+
+ ```python3
+ mo.pdf(
+ src="https://arxiv.org/pdf/2104.00282.pdf",
+ width="100%",
+ height="50vh",
+ )
+
+ with open("paper.pdf", "rb") as file:
+ mo.pdf(src=file)
+ ```
+
+ **Args.**
+
+ - `src`: the URL of the pdf or a file-like object
+ - `initial_page`: the page to open the pdf to.
+ only works if `src` is a URL
+ - `width`: the width of the pdf
+ - `height`: the height of the pdf. for a percentage
+ of the user's viewport, use a string like `"50vh"`
+ - `style`: a dictionary of CSS styles to apply to the pdf
+
+ **Returns.**
+
+ `Html` object
+ """
+ resolved_src = src if isinstance(src, str) else _io_to_data_url(src)
+ if initial_page is not None and isinstance(src, str):
+ # FitV is "fit to vertical"
+ resolved_src += f"#page={initial_page}&view=FitV"
+ styles = create_style(
+ {
+ "border-radius": "4px",
+ "width": width,
+ "height": height,
+ **(style or {}),
+ }
+ )
+ return Html(
+ h.iframe(
+ src=resolved_src,
+ style=styles,
+ )
+ )
+
+
+def _io_to_data_url(readable: io.IOBase) -> str:
+ base64_string = base64.b64encode(readable.read()).decode("utf-8")
+ return f"data:application/pdf;base64,{base64_string}"
diff --git a/marimo/_smoke_tests/pdf.py b/marimo/_smoke_tests/pdf.py
new file mode 100644
index 0000000000..5009702702
--- /dev/null
+++ b/marimo/_smoke_tests/pdf.py
@@ -0,0 +1,39 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.4"
+app = marimo.App(width="full")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mo.md("# PDFs")
+ return
+
+
+def __(mo):
+ page = mo.ui.number(1, 10, label="Starting page number")
+ page
+ return page,
+
+
+def __(mo, page):
+ mo.pdf(
+ src="https://arxiv.org/pdf/2104.00282.pdf",
+ initial_page=page.value,
+ width="100%",
+ height="60vh"
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()