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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
add new endpoint to download pdf using nbconvert & feature flag (#7894)
Shahmir Varqhab1ac91ed72c3
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.mdindex ff050c7913..77c62301c0 100644--- a/docs/guides/exporting.md+++ b/docs/guides/exporting.md@@ -124,11 +124,15 @@ marimo export ipynb notebook.py -o notebook.ipynb## Exporting to PDF, slides, or rst+### Export PDF using Quarto+The marimo [Quarto](https://www.github.com/marimo-team/quarto-marimo) pluginenables exporting to PDF and other formats with Pandoc. See this [publishing](./publishing/quarto.md) for more details.-However, if you export to a Jupyter notebook, you can leverage various other 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/).+### Export PDF from the command line++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/).```bashNOTEBOOK=notebook.ipynb@@ -166,6 +170,29 @@ You can also use other tools that work with Jupyter notebooks:- [Quarto](https://quarto.org) - Create beautiful documents, websites, presentations- [nbgrader](https://nbgrader.readthedocs.io/) - Grade notebook assignments+### Export PDF from the command palette++!!! note "Experimental feature"++ This feature is experimental. Enable it in **Settings > Experimental > Better PDF Export**.++You can export your notebook to PDF directly from the command palette (Ctrl+K) by clicking+**Download as PDF**. This uses `nbconvert` under the hood and will attempt the+following:++1. **Standard PDF export** (requires [Pandoc](https://nbconvert.readthedocs.io/en/latest/install.html#installing-pandoc) and [TeX](https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex)) — produces higher quality PDFs+2. **WebPDF fallback** (requires Chromium via [Playwright](https://playwright.dev/python/)) — automatically used if Pandoc/TeX are not installed++To install the required dependencies:++```bash+# For standard PDF export (higher quality)+uv pip install nbconvert++# For WebPDF fallback (easier setup)+uv pip install "nbconvert[webpdf]"+```+## Export to WASM-powered HTMLExport your notebook to a self-contained HTML file that runs using [WebAssembly](wasm.md):diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.tsindex 25d6629654..2a2b5ef999 100644--- a/frontend/src/__mocks__/requests.ts+++ b/frontend/src/__mocks__/requests.ts@@ -60,6 +60,7 @@ export const MockRequestClient = {shutdownSession: vi.fn().mockResolvedValue({}),exportAsHTML: vi.fn().mockResolvedValue({ html: "" }),exportAsMarkdown: vi.fn().mockResolvedValue({ markdown: "" }),+ exportAsPDF: vi.fn().mockResolvedValue(new Blob()),autoExportAsHTML: vi.fn().mockResolvedValue({}),autoExportAsMarkdown: vi.fn().mockResolvedValue({}),autoExportAsIPYNB: vi.fn().mockResolvedValue({}),diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 35e947a36c..83c5ec12d2 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1283,6 +1283,39 @@ export const UserConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="experimental.server_side_pdf_export"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">+ Better PDF Export+ </FormLabel>+ <FormControl>+ <Checkbox+ data-testid="server-side-pdf-export-checkbox"+ checked={field.value === true}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ <IsOverridden+ userConfig={config}+ name="experimental.server_side_pdf_export"+ />+ <FormDescription>+ Enable PDF export using{" "}+ <Kbd className="inline">nbconvert</Kbd> and{" "}+ <Kbd className="inline">playwright</Kbd>. Refer to{" "}+ <ExternalLink href="https://docs.marimo.io/guides/exporting/#exporting-to-pdf-slides-or-rst">+ the docs+ </ExternalLink>+ .+ </FormDescription>+ </div>+ )}+ /></SettingGroup>);}diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex 16ba74658e..21a4759a23 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -20,6 +20,7 @@ import { TextOutput } from "./output/TextOutput";import { VideoOutput } from "./output/VideoOutput";import "./output/Outputs.css";+import { useAtomValue } from "jotai";import {ChevronsDownUpIcon,ChevronsUpDownIcon,@@ -27,6 +28,7 @@ import {} from "lucide-react";import { tooltipHandler } from "@/components/charts/tooltip";import { useExpandedOutput } from "@/core/cells/outputs";+import { viewStateAtom } from "@/core/mode";import { useIframeCapabilities } from "@/hooks/useIframeCapabilities";import { renderHTML } from "@/plugins/core/RenderHTML";import { Banner } from "@/plugins/impl/common/error-banner";@@ -46,10 +48,9 @@ import { renderMimeIcon } from "./renderMimeIcon";const METADATA_KEY = "__metadata__";-type MimeBundleWithoutMetadata = Record<- OutputMessage["mimetype"],- { [key: string]: unknown }->;+export type MimeType = OutputMessage["mimetype"];++type MimeBundleWithoutMetadata = Record<MimeType, { [key: string]: unknown }>;type MimeBundle = MimeBundleWithoutMetadata & {[METADATA_KEY]?: Record<string, { width?: number; height?: number }>;@@ -70,7 +71,7 @@ export const OutputRenderer: React.FC<{onRefactorWithAI?: OnRefactorWithAI;wrapText?: boolean;metadata?: { width?: number; height?: number };- renderFallback?: (mimetype: OutputMessage["mimetype"]) => React.ReactNode;+ renderFallback?: (mimetype: MimeType) => React.ReactNode;}> = memo((props) => {const {message,@@ -220,9 +221,7 @@ export const OutputRenderer: React.FC<{return (<MimeBundleOutputRendererchannel={channel}- data={- parsedJsonData as Record<OutputMessage["mimetype"], OutputMessage>- }+ data={parsedJsonData as Record<MimeType, OutputMessage>}/>);case "application/vnd.jupyter.widget-view+json":@@ -262,6 +261,8 @@ const MimeBundleOutputRenderer: React.FC<{cellId?: CellId;}> = memo(({ data, channel, cellId }) => {const mimebundle = Array.isArray(data) ? data[0] : data;+ const { mode } = useAtomValue(viewStateAtom);+ const appView = mode === "present" || mode === "read";// Extract metadata if present (e.g., for retina image rendering)const metadata = mimebundle[METADATA_KEY];@@ -269,10 +270,7 @@ const MimeBundleOutputRenderer: React.FC<{// Filter out metadata from the mime entries and type narrowconst mimeEntries = Objects.entries(mimebundle as Record<string, unknown>).filter(([key]) => key !== METADATA_KEY)- .map(- ([mime, data]) =>- [mime, data] as [OutputMessage["mimetype"], CellOutput["data"]],- );+ .map(([mime, data]) => [mime, data] as [MimeType, CellOutput["data"]]);// If there is none, return nullconst first = mimeEntries[0]?.[0];@@ -306,7 +304,12 @@ const MimeBundleOutputRenderer: React.FC<{return (<Tabs defaultValue={first} orientation="vertical"><div className="flex">- <TabsList className="self-start max-h-none flex flex-col gap-2 mr-4 shrink-0">+ <TabsList+ className={cn(+ "self-start max-h-none flex flex-col gap-2 mr-3 shrink-0",+ appView && "mt-4",+ )}+ >{mimeEntries.map(([mime]) => (<TabsTriggerkey={mime}@@ -319,7 +322,7 @@ const MimeBundleOutputRenderer: React.FC<{</TabsTrigger>))}</TabsList>- <div className="flex-1">+ <div className="flex-1 w-full">{mimeEntries.map(([mime, output]) => (<TabsContent key={mime} value={mime}><ErrorBoundary>diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 6582bfc2c4..c3e51e80d8 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -54,7 +54,12 @@ import {} from "@/core/cells/cells";import { disabledCellIds } from "@/core/cells/utils";import { useResolvedMarimoConfig } from "@/core/config/config";+import { getFeatureFlag } from "@/core/config/feature-flag";import { Constants } from "@/core/constants";+import {+ updateCellOutputsWithScreenshots,+ useEnrichCellOutputs,+} from "@/core/export/hooks";import { useLayoutActions, useLayoutState } from "@/core/layout/layout";import { useTogglePresenting } from "@/core/layout/useTogglePresenting";import { kioskModeAtom, viewStateAtom } from "@/core/mode";@@ -64,7 +69,12 @@ import { downloadAsHTML } from "@/core/static/download-html";import { createShareableLink } from "@/core/wasm/share";import { isWasm } from "@/core/wasm/utils";import { copyToClipboard } from "@/utils/copy";-import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";+import {+ downloadAsPDF,+ downloadBlob,+ downloadHTMLAsImage,+ withLoadingToast,+} from "@/utils/download";import { Filenames } from "@/utils/filenames";import { Objects } from "@/utils/objects";import { newNotebookURL } from "@/utils/urls";@@ -110,13 +120,15 @@ export function useNotebookActions() {const setCommandPaletteOpen = useSetAtom(commandPaletteAtom);const setSettingsDialogOpen = useSetAtom(settingDialogAtom);const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);- const { exportAsMarkdown, readCode, saveCellConfig } = useRequestClient();+ const { exportAsMarkdown, readCode, saveCellConfig, updateCellOutputs } =+ useRequestClient();const hasDisabledCells = useAtomValue(hasDisabledCellsAtom);const canUndoDeletes = useAtomValue(canUndoDeletesAtom);const { selectedLayout } = useLayoutState();const { setLayoutView } = useLayoutActions();const togglePresenting = useTogglePresenting();+ const takeScreenshots = useEnrichCellOutputs();// Fallback: if sharing is undefined, both are enabled by defaultconst sharingHtmlEnabled = resolvedConfig.sharing?.html ?? true;@@ -139,11 +151,7 @@ export function useNotebookActions() {label: "Download as HTML",handle: async () => {if (!filename) {- toast({- variant: "danger",- title: "Error",- description: "Notebooks must be named to be exported.",- });+ toastNotebookMustBeNamed();return;}await downloadAsHTML({ filename, includeCode: true });@@ -154,11 +162,7 @@ export function useNotebookActions() {label: "Download as HTML (exclude code)",handle: async () => {if (!filename) {- toast({- variant: "danger",- title: "Error",- description: "Notebooks must be named to be exported.",- });+ toastNotebookMustBeNamed();return;}await downloadAsHTML({ filename, includeCode: false });@@ -220,6 +224,26 @@ export function useNotebookActions() {</span>),handle: async () => {+ if (getFeatureFlag("server_side_pdf_export")) {+ if (!filename) {+ toastNotebookMustBeNamed();+ return;+ }++ const downloadPDF = async () => {+ await updateCellOutputsWithScreenshots(+ takeScreenshots,+ updateCellOutputs,+ );+ await downloadAsPDF({+ filename: filename,+ webpdf: false,+ });+ };+ await withLoadingToast("Downloading PDF...", downloadPDF);+ return;+ }+const beforeprint = new Event("export-beforeprint");const afterprint = new Event("export-afterprint");function print() {@@ -527,3 +551,11 @@ export function useNotebookActions() {return action;});}++function toastNotebookMustBeNamed() {+ toast({+ title: "Error",+ description: "Notebooks must be named to be exported.",+ variant: "danger",+ });+}diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 797350fbde..4637ecf263 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -13,6 +13,7 @@ export interface ExperimentalFeatures {chat_modes: boolean;cache_panel: boolean;external_agents: boolean;+ server_side_pdf_export: boolean;// Add new feature flags here}@@ -24,6 +25,7 @@ const defaultValues: ExperimentalFeatures = {chat_modes: false,cache_panel: false,external_agents: import.meta.env.DEV,+ server_side_pdf_export: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/core/export/__tests__/hooks.test.ts b/frontend/src/core/export/__tests__/hooks.test.tsindex 4c65c1d172..2d3571867e 100644--- a/frontend/src/core/export/__tests__/hooks.test.ts+++ b/frontend/src/core/export/__tests__/hooks.test.ts@@ -8,7 +8,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { CellId } from "@/core/cells/ids";import { CellOutputId } from "@/core/cells/ids";import type { CellRuntimeState } from "@/core/cells/types";-import { useEnrichCellOutputs } from "../hooks";+import {+ updateCellOutputsWithScreenshots,+ useEnrichCellOutputs,+} from "../hooks";// Mock html-to-imagevi.mock("html-to-image", () => ({@@ -22,6 +25,11 @@ vi.mock("@/utils/Logger", () => ({},}));+// Mock toast+vi.mock("@/components/ui/use-toast", () => ({+ toast: vi.fn(),+}));+// Mock cellsRuntimeAtom - must be defined inline in the factory functionvi.mock("@/core/cells/cells", async () => {const { atom } = await import("jotai");@@ -31,6 +39,7 @@ vi.mock("@/core/cells/cells", async () => {});import { toPng } from "html-to-image";+import { toast } from "@/components/ui/use-toast";import { cellsRuntimeAtom } from "@/core/cells/cells";import { Logger } from "@/utils/Logger";@@ -502,3 +511,113 @@ describe("useEnrichCellOutputs", () => {}});});++describe("updateCellOutputsWithScreenshots", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("should call updateCellOutputs when there are screenshots", async () => {+ const cellId = "cell-1" as CellId;+ const mockScreenshots = {+ [cellId]: ["image/png", "data:image/png;base64,test"] as [+ "image/png",+ string,+ ],+ };++ const takeScreenshots = vi.fn().mockResolvedValue(mockScreenshots);+ const updateCellOutputs = vi.fn().mockResolvedValue(null);++ await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);++ expect(takeScreenshots).toHaveBeenCalledTimes(1);+ expect(updateCellOutputs).toHaveBeenCalledTimes(1);+ expect(updateCellOutputs).toHaveBeenCalledWith({+ cellIdsToOutput: mockScreenshots,+ });+ });++ it("should not call updateCellOutputs when there are no screenshots", async () => {+ const takeScreenshots = vi.fn().mockResolvedValue({});+ const updateCellOutputs = vi.fn().mockResolvedValue(null);++ await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);++ expect(takeScreenshots).toHaveBeenCalledTimes(1);+ expect(updateCellOutputs).not.toHaveBeenCalled();+ });++ it("should handle multiple cell screenshots", async () => {+ const cell1 = "cell-1" as CellId;+ const cell2 = "cell-2" as CellId;+ const mockScreenshots = {+ [cell1]: ["image/png", "data:image/png;base64,image1"] as [+ "image/png",+ string,+ ],+ [cell2]: ["image/png", "data:image/png;base64,image2"] as [+ "image/png",+ string,+ ],+ };++ const takeScreenshots = vi.fn().mockResolvedValue(mockScreenshots);+ const updateCellOutputs = vi.fn().mockResolvedValue(null);++ await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);++ expect(updateCellOutputs).toHaveBeenCalledWith({+ cellIdsToOutput: mockScreenshots,+ });+ });++ it("should catch errors from takeScreenshots and show toast", async () => {+ const error = new Error("Screenshot failed");+ const takeScreenshots = vi.fn().mockRejectedValue(error);+ const updateCellOutputs = vi.fn().mockResolvedValue(null);++ // Should not throw - errors are caught and shown via toast+ await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);++ expect(updateCellOutputs).not.toHaveBeenCalled();+ expect(Logger.error).toHaveBeenCalledWith(+ "Error updating cell outputs with screenshots:",+ error,+ );+ expect(toast).toHaveBeenCalledWith({+ title: "Failed to capture cell outputs",+ description:+ "Some outputs may not appear in the PDF. Continuing with export.",+ variant: "danger",+ });+ });++ it("should catch errors from updateCellOutputs and show toast", async () => {+ const cellId = "cell-1" as CellId;+ const mockScreenshots = {+ [cellId]: ["image/png", "data:image/png;base64,test"] as [+ "image/png",+ string,+ ],+ };+ const error = new Error("Update failed");++ const takeScreenshots = vi.fn().mockResolvedValue(mockScreenshots);+ const updateCellOutputs = vi.fn().mockRejectedValue(error);++ // Should not throw - errors are caught and shown via toast+ await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);++ expect(Logger.error).toHaveBeenCalledWith(+ "Error updating cell outputs with screenshots:",+ error,+ );+ expect(toast).toHaveBeenCalledWith({+ title: "Failed to capture cell outputs",+ description:+ "Some outputs may not appear in the PDF. Continuing with export.",+ variant: "danger",+ });+ });+});diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.tsindex 386bbf5f3c..87a3c0c941 100644--- a/frontend/src/core/export/hooks.ts+++ b/frontend/src/core/export/hooks.ts@@ -1,6 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */import { toPng } from "html-to-image";import { atom, useAtom, useAtomValue } from "jotai";+import type { MimeType } from "@/components/editor/Output";+import { toast } from "@/components/ui/use-toast";import { appConfigAtom } from "@/core/config/config";import { useInterval } from "@/hooks/useInterval";import { Logger } from "@/utils/Logger";@@ -9,6 +11,7 @@ import { cellsRuntimeAtom } from "../cells/cells";import { type CellId, CellOutputId } from "../cells/ids";import { connectionAtom } from "../network/connection";import { useRequestClient } from "../network/requests";+import type { UpdateCellOutputsRequest } from "../network/types";import { VirtualFileTracker } from "../static/virtual-file-tracker";import { WebSocketState } from "../websocket/types";@@ -60,12 +63,10 @@ export function useAutoExport() {useInterval(async () => {- const cellsToOutput = await takeScreenshots();- if (Object.keys(cellsToOutput).length > 0) {- await updateCellOutputs({- cellIdsToOutput: cellsToOutput,- });- }+ await updateCellOutputsWithScreenshots(+ takeScreenshots,+ updateCellOutputs,+ );await autoExportAsIPYNB({download: false,});@@ -86,7 +87,7 @@ export function useAutoExport() {const richCellsToOutputAtom = atom<Record<CellId, unknown>>({});// MIME types to capture screenshots for-const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set([+const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set<MimeType>(["text/html","application/vnd.vegalite.v5+json","application/vnd.vega.v5+json",@@ -112,7 +113,8 @@ export function useEnrichCellOutputs() {// Track latest output for this celltrackedCellsOutput[cellId] = outputData;if (- MIME_TYPES_TO_CAPTURE_SCREENSHOTS.has(runtime.output?.mimetype ?? "") &&+ runtime.output?.mimetype &&+ MIME_TYPES_TO_CAPTURE_SCREENSHOTS.has(runtime.output.mimetype) &&outputData &&outputHasChanged) {@@ -157,3 +159,26 @@ export function useEnrichCellOutputs() {);};}++/**+ * Utility function to take screenshots of cells with HTML outputs and update the cell outputs.+ */+export async function updateCellOutputsWithScreenshots(+ takeScreenshots: () => Promise<Record<CellId, ["image/png", string]>>,+ updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>,+) {+ try {+ const cellIdsToOutput = await takeScreenshots();+ if (Object.keys(cellIdsToOutput).length > 0) {+ await updateCellOutputs({ cellIdsToOutput });+ }+ } catch (error) {+ Logger.error("Error updating cell outputs with screenshots:", error);+ toast({+ title: "Failed to capture cell outputs",+ description:+ "Some outputs may not appear in the PDF. Continuing with export.",+ variant: "danger",+ });+ }+}diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex 993e1885a2..df06094a0c 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -168,6 +168,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {openTutorial = throwNotImplemented;exportAsHTML = throwNotImplemented;exportAsMarkdown = throwNotImplemented;+ exportAsPDF = throwNotImplemented;autoExportAsHTML = throwNotImplemented;autoExportAsMarkdown = throwNotImplemented;autoExportAsIPYNB = throwNotImplemented;diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.tsindex edca97304d..86bb7faf8f 100644--- a/frontend/src/core/network/requests-lazy.ts+++ b/frontend/src/core/network/requests-lazy.ts@@ -50,6 +50,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {// Export operations start a connectionexportAsHTML: "startConnection",exportAsMarkdown: "startConnection",+ exportAsPDF: "startConnection",readCode: "startConnection",sendCopy: "throwError",diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 662298d83f..a26c16d7db 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -381,6 +381,15 @@ export function createNetworkRequests(): EditRequests & RunRequests {}).then(handleResponse);},+ exportAsPDF: async (request) => {+ return getClient()+ .POST("/api/export/pdf", {+ body: request,+ parseAs: "blob",+ params: getParams(),+ })+ .then(handleResponse);+ },autoExportAsHTML: async (request) => {return getClient().POST("/api/export/auto_export/html", {diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.tsindex 4311c9ee22..a82e971e0d 100644--- a/frontend/src/core/network/requests-static.ts+++ b/frontend/src/core/network/requests-static.ts@@ -76,6 +76,7 @@ export function createStaticRequests(): EditRequests & RunRequests {shutdownSession: throwNotInEditMode,exportAsHTML: throwNotInEditMode,exportAsMarkdown: throwNotInEditMode,+ exportAsPDF: throwNotInEditMode,autoExportAsHTML: throwNotInEditMode,autoExportAsMarkdown: throwNotInEditMode,autoExportAsIPYNB: throwNotInEditMode,diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsxindex a39df411f4..5cd32078bb 100644--- a/frontend/src/core/network/requests-toasting.tsx+++ b/frontend/src/core/network/requests-toasting.tsx@@ -61,6 +61,7 @@ export function createErrorToastingRequests(shutdownSession: "Failed to shutdown session",exportAsHTML: "Failed to export HTML",exportAsMarkdown: "Failed to export Markdown",+ exportAsPDF: "Failed to export PDF",autoExportAsHTML: "", // No toastautoExportAsMarkdown: "", // No toastautoExportAsIPYNB: "", // No toastdiff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 9b2ee1b8aa..977dc2f8a2 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -21,6 +21,7 @@ export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];export type ExportAsMarkdownRequest = schemas["ExportAsMarkdownRequest"];export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];export type ExportAsScriptRequest = schemas["ExportAsScriptRequest"];+export type ExportAsPDFRequest = schemas["ExportAsPDFRequest"];export type UpdateCellOutputsRequest = schemas["UpdateCellOutputsRequest"];export type FileCreateRequest = schemas["FileCreateRequest"];export type FileCreateResponse = schemas["FileCreateResponse"];@@ -173,6 +174,7 @@ export interface EditRequests {// Export requestsexportAsHTML: (request: ExportAsHTMLRequest) => Promise<string>;exportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<string>;+ exportAsPDF: (request: ExportAsPDFRequest) => Promise<Blob>;autoExportAsHTML: (request: ExportAsHTMLRequest) => Promise<null>;autoExportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<null>;autoExportAsIPYNB: (request: ExportAsIPYNBRequest) => Promise<null>;diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex 6fad95f10a..b95e7874c4 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -586,6 +586,7 @@ export class PyodideBridge implements RunRequests, EditRequests {getWorkspaceFiles = throwNotImplemented;getRunningNotebooks = throwNotImplemented;shutdownSession = throwNotImplemented;+ exportAsPDF = throwNotImplemented;autoExportAsHTML = throwNotImplemented;autoExportAsMarkdown = throwNotImplemented;autoExportAsIPYNB = throwNotImplemented;diff --git a/frontend/src/utils/__tests__/download.test.tsx b/frontend/src/utils/__tests__/download.test.tsxnew file mode 100644index 0000000000..d93bc7d386--- /dev/null+++ b/frontend/src/utils/__tests__/download.test.tsx@@ -0,0 +1,96 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { beforeEach, describe, expect, it, vi } from "vitest";+import { withLoadingToast } from "../download";++// Mock the toast module+const mockDismiss = vi.fn();+vi.mock("@/components/ui/use-toast", () => ({+ toast: vi.fn(() => ({+ dismiss: mockDismiss,+ })),+}));++// Mock the Spinner component+vi.mock("@/components/icons/spinner", () => ({+ Spinner: () => "MockSpinner",+}));++import { toast } from "@/components/ui/use-toast";++describe("withLoadingToast", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("should show a loading toast and dismiss on success", async () => {+ const result = await withLoadingToast("Loading...", async () => {+ return "success";+ });++ expect(toast).toHaveBeenCalledTimes(1);+ expect(toast).toHaveBeenCalledWith({+ title: "Loading...",+ });+ expect(mockDismiss).toHaveBeenCalledTimes(1);+ expect(result).toBe("success");+ });++ it("should dismiss toast and rethrow on error", async () => {+ const error = new Error("Operation failed");++ await expect(+ withLoadingToast("Loading...", async () => {+ throw error;+ }),+ ).rejects.toThrow("Operation failed");++ expect(toast).toHaveBeenCalledTimes(1);+ expect(mockDismiss).toHaveBeenCalledTimes(1);+ });++ it("should return the value from the async function", async () => {+ const expectedValue = { data: "test", count: 42 };++ const result = await withLoadingToast("Processing...", async () => {+ return expectedValue;+ });++ expect(result).toEqual(expectedValue);+ });++ it("should handle void functions", async () => {+ let sideEffect = false;++ await withLoadingToast("Saving...", async () => {+ sideEffect = true;+ });++ expect(sideEffect).toBe(true);+ expect(mockDismiss).toHaveBeenCalledTimes(1);+ });++ it("should use the provided title in the toast", async () => {+ const customTitle = "Downloading PDF...";++ await withLoadingToast(customTitle, async () => "done");++ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: customTitle,+ }),+ );+ });++ it("should wait for the async function to complete", async () => {+ const events: string[] = [];++ await withLoadingToast("Loading...", async () => {+ events.push("start");+ await new Promise((resolve) => setTimeout(resolve, 10));+ events.push("end");+ });++ expect(events).toEqual(["start", "end"]);+ expect(mockDismiss).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsindex 40ab19aae0..94822a2d7d 100644--- a/frontend/src/utils/download.ts+++ b/frontend/src/utils/download.ts@@ -1,7 +1,31 @@/* Copyright 2026 Marimo. All rights reserved. */import { toPng } from "html-to-image";import { toast } from "@/components/ui/use-toast";+import { getRequestClient } from "@/core/network/requests";import { Filenames } from "@/utils/filenames";+import { Paths } from "@/utils/paths";+import { prettyError } from "./errors";++/**+ * Show a loading toast while an async operation is in progress.+ * Automatically dismisses the toast when the operation completes or fails.+ */+export async function withLoadingToast<T>(+ title: string,+ fn: () => Promise<T>,+): Promise<T> {+ const loadingToast = toast({+ title,+ });+ try {+ const result = await fn();+ loadingToast.dismiss();+ return result;+ } catch (error) {+ loadingToast.dismiss();+ throw error;+ }+}export async function downloadHTMLAsImage(element: HTMLElement,@@ -45,3 +69,33 @@ export function downloadBlob(blob: Blob, filename: string) {downloadByURL(url, filename);URL.revokeObjectURL(url);}++/**+ * Download the current notebook as a PDF file.+ *+ * WebPDF only requires Chromium to be installed.+ * Standard PDF requires Pandoc & TeX (~few GBs) but is of higher quality.+ */+export async function downloadAsPDF(opts: {+ filename: string;+ webpdf: boolean;+}) {+ const client = getRequestClient();+ const { filename, webpdf } = opts;++ try {+ const pdfBlob = await client.exportAsPDF({+ webpdf,+ });++ const filenameWithoutPath = Paths.basename(filename);+ downloadBlob(pdfBlob, Filenames.toPDF(filenameWithoutPath));+ } catch (error) {+ toast({+ title: "Failed to download",+ description: prettyError(error),+ variant: "danger",+ });+ throw error;+ }+}diff --git a/frontend/src/utils/filenames.ts b/frontend/src/utils/filenames.tsindex adc3cb99b2..6c91268ec1 100644--- a/frontend/src/utils/filenames.ts+++ b/frontend/src/utils/filenames.ts@@ -9,6 +9,9 @@ export const Filenames = {toPNG: (filename: string): string => {return Filenames.replace(filename, "png");},+ toPDF: (filename: string): string => {+ return Filenames.replace(filename, "pdf");+ },toPY: (filename: string): string => {return Filenames.replace(filename, "py");},diff --git a/marimo/_ast/fast_stack.py b/marimo/_ast/fast_stack.pyindex 7f49a43969..ed56854030 100644--- a/marimo/_ast/fast_stack.py+++ b/marimo/_ast/fast_stack.py@@ -1,3 +1,4 @@+# Copyright 2026 Marimo. All rights reserved.# Source - https://stackoverflow.com/a# Posted by Kache, modified by community. See post 'Timeline' for change history# Retrieved 2026-01-17, License - CC BY-SA 4.0diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex a4a9d989e2..b48f664b02 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -155,6 +155,7 @@ def _generate_server_api_schema() -> dict[str, Any]:export.ExportAsMarkdownRequest,export.ExportAsScriptRequest,export.ExportAsIPYNBRequest,+ export.ExportAsPDFRequest,export.UpdateCellOutputsRequest,files.FileCreateRequest,files.FileCreateResponse,diff --git a/marimo/_convert/ipynb/from_ir.py b/marimo/_convert/ipynb/from_ir.pyindex fa9129ecf3..53b3be9a39 100644--- a/marimo/_convert/ipynb/from_ir.py+++ b/marimo/_convert/ipynb/from_ir.py@@ -198,6 +198,15 @@ def _maybe_extract_dataurl(data: Any) -> Any:return data+def _is_marimo_component(html_content: Any) -> bool:+ """Check if the content is a marimo component."""+ if isinstance(html_content, list):+ html_content = "".join(html_content)+ if not isinstance(html_content, str):+ return False+ return "<marimo-" in html_content++class _HTMLTextExtractor(HTMLParser):"""Extract plain text from HTML."""@@ -348,6 +357,9 @@ def _convert_marimo_output_to_ipynb(for mime, content in mimebundle.items():if mime == METADATA_KEY and isinstance(content, dict):metadata = content+ elif mime == "text/html" and _is_marimo_component(content):+ # Skip marimo components because they cannot be rendered in IPython notebook format+ continueelse:data[mime] = _maybe_extract_dataurl(content)else:diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 001a365e58..49092a0c58 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -211,6 +211,8 @@ class DependencyManager:ipython = Dependency("IPython")ipywidgets = Dependency("ipywidgets")nbformat = Dependency("nbformat")+ nbconvert = Dependency("nbconvert")+ playwright = Dependency("playwright") # installed by nbconvert[webpdf]narwhals = Dependency("narwhals")ruff = Dependency("ruff")black = Dependency("black")diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex f93347fea0..820384088a 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -6,7 +6,12 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.background import BackgroundTaskfrom starlette.exceptions import HTTPException-from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse+from starlette.responses import (+ HTMLResponse,+ JSONResponse,+ PlainTextResponse,+ Response,+)from marimo import _loggersfrom marimo._convert.common.filename import (@@ -23,6 +28,7 @@ from marimo._server.export.exporter import AutoExporter, Exporterfrom marimo._server.models.export import (ExportAsHTMLRequest,ExportAsMarkdownRequest,+ ExportAsPDFRequest,ExportAsScriptRequest,UpdateCellOutputsRequest,)@@ -419,6 +425,61 @@ async def auto_export_as_ipynb()[email protected]("/pdf")+@requires("edit")+async def export_as_pdf(*, request: Request) -> Response:+ """+ parameters:+ - in: header+ name: Marimo-Session-Id+ schema:+ type: string+ required: true+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ExportAsPDFRequest"+ responses:+ 200:+ description: Export the notebook as a PDF+ content:+ application/pdf:+ schema:+ type: string+ format: binary+ 400:+ description: File must be saved before downloading+ 500:+ description: Export failed or dependencies missing+ """+ app_state = AppState(request)+ body = await parse_request(request, cls=ExportAsPDFRequest)+ session = app_state.require_current_session()++ if not session.app_file_manager.is_notebook_named:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File must have a name before exporting",+ )++ pdf_data = Exporter().export_as_pdf(+ app=session.app_file_manager.app,+ session_view=session.session_view,+ webpdf=body.webpdf,+ )+ if pdf_data is None:+ raise HTTPException(+ status_code=HTTPStatus.SERVER_ERROR, detail="Failed to export PDF"+ )+ filename = get_download_filename(session.app_file_manager.filename, "pdf")+ headers = make_download_headers(filename)++ return Response(+ content=pdf_data, media_type="application/pdf", headers=headers+ )++@router.post("/update_cell_outputs")@requires("edit")async def update_cell_outputs(diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex a78cf0c0e9..4ce8228651 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -26,6 +26,7 @@ from marimo._convert.common.filename import (get_filename,)from marimo._convert.ipynb.from_ir import convert_from_ir_to_ipynb+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._runtime.virtual_file import read_virtual_filefrom marimo._schemas.notebook import NotebookV1@@ -305,6 +306,67 @@ class Exporter:return html, download_filename+ def export_as_pdf(+ self, *, app: InternalApp, session_view: SessionView, webpdf: bool+ ) -> bytes | None:+ """Export notebook as a PDF.++ Args:+ app: The app to export+ session_view: The session view to export+ webpdf: If False, tries standard PDF export (pandoc + TeX) first,+ falling back to webpdf if deps are not installed. If True, uses webpdf+ directly.++ Returns:+ PDF data+ """+ DependencyManager.require_many(+ "for PDF export",+ DependencyManager.nbformat,+ DependencyManager.nbconvert,+ )++ ipynb_json_str = self.export_as_ipynb(+ app=app, sort_mode="top-down", session_view=session_view+ )++ import nbformat++ notebook = nbformat.reads(ipynb_json_str, as_version=4) # type: ignore[no-untyped-call]++ # Try standard PDF export first (requires pandoc + TeX)+ # and fall back to webpdf if it fails+ if not webpdf:+ try:+ from nbconvert import ( # type: ignore[import-not-found]+ PDFExporter,+ )++ exporter = PDFExporter()+ pdf_data, _resources = exporter.from_notebook_node(notebook)+ if isinstance(pdf_data, bytes):+ return pdf_data+ LOGGER.error("PDF data is not bytes: %s", pdf_data)+ return None+ except OSError as e:+ LOGGER.warning(+ "Standard PDF export failed, falling back to webpdf. Error: %s",+ e,+ )++ DependencyManager.playwright.require("for webpdf export")+ from nbconvert import WebPDFExporter # type: ignore[import-not-found]++ web_exporter = WebPDFExporter()+ web_exporter.allow_chromium_download = True+ pdf_data, _resources = web_exporter.from_notebook_node(notebook)++ if not isinstance(pdf_data, bytes):+ LOGGER.error("PDF data is not bytes: %s", pdf_data)+ return None+ return pdf_data+def export_assets(self, directory: Path, ignore_index_html: bool = False) -> None:diff --git a/marimo/_server/models/export.py b/marimo/_server/models/export.pyindex 33d23bb507..047fca6200 100644--- a/marimo/_server/models/export.py+++ b/marimo/_server/models/export.py@@ -28,5 +28,9 @@ class ExportAsMarkdownRequest(msgspec.Struct, rename="camel"):download: bool+class ExportAsPDFRequest(msgspec.Struct, rename="camel"):+ webpdf: bool++class UpdateCellOutputsRequest(msgspec.Struct, rename="camel"):cell_ids_to_output: dict[CellId_t, MimeBundleTuple]diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 26915e695a..52508ccc0b 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1492,6 +1492,14 @@ components:- downloadtitle: ExportAsMarkdownRequesttype: object+ ExportAsPDFRequest:+ properties:+ webpdf:+ type: boolean+ required:+ - webpdf+ title: ExportAsPDFRequest+ type: objectExportAsScriptRequest:properties:download:@@ -4844,6 +4852,31 @@ paths:description: Export the notebook as a markdown400:description: File must be saved before downloading+ /api/export/pdf:+ post:+ parameters:+ - in: header+ name: Marimo-Session-Id+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ExportAsPDFRequest'+ responses:+ 200:+ content:+ application/pdf:+ schema:+ format: binary+ type: string+ description: Export the notebook as a PDF+ 400:+ description: File must be saved before downloading+ 500:+ description: Export failed or dependencies missing/api/export/script:post:parameters:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex ed05991de0..6aaeddff09 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -804,6 +804,61 @@ export interface paths {patch?: never;trace?: never;};+ "/api/export/pdf": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header: {+ "Marimo-Session-Id": string;+ };+ path?: never;+ cookie?: never;+ };+ requestBody?: {+ content: {+ "application/json": components["schemas"]["ExportAsPDFRequest"];+ };+ };+ responses: {+ /** @description Export the notebook as a PDF */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/pdf": string;+ };+ };+ /** @description File must be saved before downloading */+ 400: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Export failed or dependencies missing */+ 500: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ };+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/export/script": {parameters: {query?: never;@@ -3809,6 +3864,10 @@ export interface components {ExportAsMarkdownRequest: {download: boolean;};+ /** ExportAsPDFRequest */+ ExportAsPDFRequest: {+ webpdf: boolean;+ };/** ExportAsScriptRequest */ExportAsScriptRequest: {download: boolean;diff --git a/tests/_convert/ipynb/test_from_ir.py b/tests/_convert/ipynb/test_from_ir.pyindex 35fa31438c..819e2ad351 100644--- a/tests/_convert/ipynb/test_from_ir.py+++ b/tests/_convert/ipynb/test_from_ir.py@@ -11,6 +11,7 @@ from marimo._ast.load import load_appfrom marimo._convert.ipynb import convert_from_ir_to_ipynbfrom marimo._convert.ipynb.from_ir import (_convert_marimo_output_to_ipynb,+ _is_marimo_component,_maybe_extract_dataurl,)from marimo._messaging.cell_output import CellChannel, CellOutput@@ -349,3 +350,159 @@ def test_convert_marimo_mimebundle_with_both_output_and_console() -> None:assert main_result[0]["output_type"] == "display_data"assert main_result[0]["data"]["text/plain"] == "Result"assert main_result[0]["data"]["image/png"] == "PNG_DATA"+++ ("html_content", "expected"),+ [+ # Marimo components should be detected+ ("<marimo-plotly data-figure='{}'>", True),+ ("<marimo-table data-data='[]'>", True),+ ("<marimo-slider value='5'>", True),+ ('<marimo-output data-output="test">', True),+ # List of strings (as Jupyter stores text/html)+ (["<marimo-plotly data-figure='{}'>"], True),+ (["<div>", "<marimo-chart>", "</div>"], True),+ # Regular HTML should not be detected+ ("<div>Hello World</div>", False),+ ("<p>Some <b>text</b></p>", False),+ ("<script>console.log('test')</script>", False),+ # Edge cases+ ("", False),+ ("marimo-plotly", False), # Not an HTML tag+ ("<div>marimo-test</div>", False), # Not a marimo tag+ # Non-string types+ (123, False),+ (None, False),+ ({"key": "value"}, False),+ ],+ ids=[+ "marimo_plotly",+ "marimo_table",+ "marimo_slider",+ "marimo_output",+ "list_with_marimo",+ "list_marimo_nested",+ "regular_div",+ "regular_paragraph",+ "regular_script",+ "empty_string",+ "marimo_text_not_tag",+ "marimo_in_text_not_tag",+ "integer",+ "none",+ "dict",+ ],+)+def test_is_marimo_component(html_content: Any, expected: bool) -> None:+ """Test _is_marimo_component detection of marimo custom elements."""+ assert _is_marimo_component(html_content) == expected+++def test_convert_mimebundle_filters_marimo_components() -> None:+ """Test that marimo components in text/html are filtered out of mimebundle."""+ # Mimebundle with marimo-plotly HTML and PNG fallback+ mimebundle = {+ "text/html": "<marimo-plotly data-figure='{\"data\": []}'>",+ "image/png": "data:image/png;base64,iVBORw0KGgo=",+ }++ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data=json.dumps(mimebundle),+ )++ result = _convert_marimo_output_to_ipynb(output, [])++ # text/html should be filtered out because it contains a marimo component+ assert result == [+ {+ "output_type": "display_data",+ "data": {+ "image/png": "iVBORw0KGgo="+ }, # image/png should remain (with data URL prefix stripped)+ "metadata": {},+ }+ ]+++def test_convert_mimebundle_keeps_regular_html() -> None:+ """Test that regular HTML is preserved in mimebundle."""+ mimebundle = {+ "text/html": "<div><p>Regular HTML content</p></div>",+ "image/png": "PNG_DATA",+ }++ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data=json.dumps(mimebundle),+ )++ result = _convert_marimo_output_to_ipynb(output, [])++ assert result == [+ {+ "output_type": "display_data",+ "data": {+ "text/html": "<div><p>Regular HTML content</p></div>",+ "image/png": "PNG_DATA",+ },+ "metadata": {},+ }+ ]+++def test_convert_mimebundle_marimo_component_only_png_remains() -> None:+ """Test mimebundle with only marimo HTML and PNG produces only PNG output."""+ mimebundle = {+ "text/html": ["<marimo-table data-data='[]'>"], # List format+ "image/png": "VALID_PNG_DATA",+ }++ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data=mimebundle, # Dict format, not JSON string+ )++ result = _convert_marimo_output_to_ipynb(output, [])++ assert result == [+ {+ "output_type": "display_data",+ "data": {"image/png": "VALID_PNG_DATA"},+ "metadata": {},+ }+ ]+++def test_convert_mimebundle_marimo_component_preserves_other_mimes() -> None:+ """Test that filtering marimo HTML preserves other MIME types."""+ mimebundle = {+ "text/html": "<marimo-slider value='5'>",+ "text/plain": "Slider(value=5)",+ "image/png": "PNG_DATA",+ "application/json": {"value": 5},+ }++ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data=json.dumps(mimebundle),+ )++ result = _convert_marimo_output_to_ipynb(output, [])++ assert result == [+ {+ "output_type": "display_data",+ "data": {+ "text/plain": "Slider(value=5)",+ "image/png": "PNG_DATA",+ "application/json": {"value": 5},+ },+ "metadata": {},+ }+ ]diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 4142adc79d..e54fd3be47 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -678,3 +678,115 @@ def test_update_cell_outputs_missing_cell(client: TestClient) -> None:# Should succeed but log a warningassert response.status_code == 200assert response.json() == {"success": True}+++@with_session(SESSION_ID)+def test_update_cell_outputs_empty_request(client: TestClient) -> None:+ """Test updating cell outputs with empty cellIdsToOutput."""+ response = client.post(+ "/api/export/update_cell_outputs",+ headers=HEADERS,+ json={"cellIdsToOutput": {}},+ )++ # Should succeed even with empty request+ assert response.status_code == 200+ assert response.json() == {"success": True}+++ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+)+@with_session(SESSION_ID)+def test_export_pdf_endpoint(client: TestClient) -> None:+ """Test PDF export endpoint."""+ from unittest.mock import MagicMock, patch++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"++ # Mock the exporter to avoid needing LaTeX/Chromium+ mock_exporter = MagicMock()+ mock_exporter.export_as_pdf.return_value = b"mock_pdf_content"++ with patch(+ "marimo._server.api.endpoints.export.Exporter",+ return_value=mock_exporter,+ ):+ response = client.post(+ "/api/export/pdf",+ headers=HEADERS,+ json={"webpdf": False},+ )++ assert response.status_code == 200+ assert response.content == b"mock_pdf_content"+ assert response.headers["content-type"] == "application/pdf"+++ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+)+@with_session(SESSION_ID)+def test_export_pdf_endpoint_webpdf_mode(client: TestClient) -> None:+ """Test PDF export endpoint with webpdf mode."""+ from unittest.mock import MagicMock, patch++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"++ # Mock the exporter to avoid needing Chromium+ mock_exporter = MagicMock()+ mock_exporter.export_as_pdf.return_value = b"mock_webpdf_content"++ with patch(+ "marimo._server.api.endpoints.export.Exporter",+ return_value=mock_exporter,+ ):+ response = client.post(+ "/api/export/pdf",+ headers=HEADERS,+ json={"webpdf": True},+ )++ assert response.status_code == 200+ assert response.content == b"mock_webpdf_content"+ # Verify webpdf=True was passed to exporter+ mock_exporter.export_as_pdf.assert_called_once()+ call_kwargs = mock_exporter.export_as_pdf.call_args[1]+ assert call_kwargs["webpdf"] is True+++@with_session(SESSION_ID)+def test_export_pdf_endpoint_returns_error_on_failure(+ client: TestClient,+) -> None:+ """Test PDF export endpoint returns error when export fails."""+ from unittest.mock import MagicMock, patch++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"++ # Mock the exporter to return None (failure case)+ mock_exporter = MagicMock()+ mock_exporter.export_as_pdf.return_value = None++ with patch(+ "marimo._server.api.endpoints.export.Exporter",+ return_value=mock_exporter,+ ):+ response = client.post(+ "/api/export/pdf",+ headers=HEADERS,+ json={"webpdf": False},+ )++ assert response.status_code == 500+ assert "Failed to export PDF" in response.textdiff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 2b075c2c69..a58400b374 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -13,7 +13,8 @@ import pytestfrom marimo._ast.app import App, InternalAppfrom marimo._ast.load import load_appfrom marimo._config.config import DEFAULT_CONFIG-from marimo._dependencies.dependencies import DependencyManager+from marimo._dependencies.dependencies import Dependency, DependencyManager+from marimo._dependencies.errors import ManyModulesNotFoundErrorfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.msgspec_encoder import encode_json_strfrom marimo._messaging.notification import CellNotification@@ -876,3 +877,252 @@ def test_export_html_replaces_multiple_virtual_files_complex(assert "data:image/png;base64," in htmlassert "data:image/svg+xml;base64," in htmlassert "https://example.com/external.png" in html+++class TestPDFExport:+ def test_export_as_pdf_requires_dependencies(+ self,+ session_view: SessionView,+ ) -> None:+ """Test that PDF export raises error when dependencies are missing."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Mock nbformat as missing+ with patch.object(Dependency, "has", return_value=False):+ with pytest.raises(ManyModulesNotFoundError) as excinfo:+ exporter.export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=False,+ )++ assert "for PDF export" in str(excinfo.value)++ @pytest.mark.skipif(+ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+ )+ def test_export_as_pdf_webpdf_requires_playwright(+ self,+ session_view: SessionView,+ ) -> None:+ """Test that webpdf mode requires playwright dependency."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Simulate nbformat and nbconvert available, but playwright missing+ def mock_has(self: Dependency, quiet: bool = False) -> bool:+ del quiet+ if self.pkg == "playwright":+ return False+ if self.pkg in ("nbformat", "nbconvert"):+ return True+ return False++ with patch.object(Dependency, "has", mock_has):+ with pytest.raises(ModuleNotFoundError) as excinfo:+ exporter.export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=True,+ )++ assert "playwright" in str(excinfo.value)++ @pytest.mark.skipif(+ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+ )+ def test_export_as_pdf_non_webpdf_mode(+ self,+ session_view: SessionView,+ ) -> None:+ """Test PDF export in non-webpdf mode (mocked)."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Mock PDFExporter to avoid requiring LaTeX+ mock_exporter_instance = MagicMock()+ mock_exporter_instance.from_notebook_node.return_value = (+ b"mock_pdf_data",+ {},+ )++ with patch("nbconvert.PDFExporter") as mock_pdf_exporter:+ mock_pdf_exporter.return_value = mock_exporter_instance++ result = exporter.export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=False,+ )++ assert result == b"mock_pdf_data"+ mock_pdf_exporter.assert_called_once()+ mock_exporter_instance.from_notebook_node.assert_called_once()++ @pytest.mark.skipif(+ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+ )+ def test_export_as_pdf_webpdf_mode(+ self,+ session_view: SessionView,+ ) -> None:+ """Test PDF export in webpdf mode (mocked)."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Mock WebPDFExporter+ mock_exporter_instance = MagicMock()+ mock_exporter_instance.from_notebook_node.return_value = (+ b"mock_webpdf_data",+ {},+ )++ # Mock playwright as available+ with (+ patch.object(+ DependencyManager.playwright, "has", return_value=True+ ),+ patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,+ ):+ mock_webpdf_exporter.return_value = mock_exporter_instance++ result = exporter.export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=True,+ )++ assert result == b"mock_webpdf_data"+ mock_webpdf_exporter.assert_called_once()+ # Verify allow_chromium_download is set+ assert mock_exporter_instance.allow_chromium_download is True++ @pytest.mark.skipif(+ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+ )+ def test_export_as_pdf_returns_none_on_invalid_data(+ self,+ session_view: SessionView,+ ) -> None:+ """Test PDF export returns None when exporter returns non-bytes data."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Mock PDFExporter to return invalid data+ mock_exporter_instance = MagicMock()+ mock_exporter_instance.from_notebook_node.return_value = (+ "not_bytes", # Invalid - should be bytes+ {},+ )++ with patch("nbconvert.PDFExporter") as mock_pdf_exporter:+ mock_pdf_exporter.return_value = mock_exporter_instance++ result = exporter.export_as_pdf(+ app=file_manager.app, session_view=session_view, webpdf=False+ )++ assert result is None++ @pytest.mark.skipif(+ not DependencyManager.nbformat.has()+ or not DependencyManager.nbconvert.has(),+ reason="nbformat or nbconvert not installed",+ )+ def test_export_as_pdf_falls_back_to_webpdf_on_oserror(+ self,+ session_view: SessionView,+ ) -> None:+ """Test PDF export falls back to webpdf when standard PDF fails with OSError."""++ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ exporter = Exporter()++ # Mock PDFExporter to raise OSError (pandoc/xelatex not found)+ mock_pdf_exporter_instance = MagicMock()+ mock_pdf_exporter_instance.from_notebook_node.side_effect = OSError(+ "xelatex not found"+ )++ # Mock WebPDFExporter to succeed+ mock_webpdf_exporter_instance = MagicMock()+ mock_webpdf_exporter_instance.from_notebook_node.return_value = (+ b"fallback_webpdf_data",+ {},+ )++ with (+ patch("nbconvert.PDFExporter") as mock_pdf_exporter,+ patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,+ ):+ mock_pdf_exporter.return_value = mock_pdf_exporter_instance+ mock_webpdf_exporter.return_value = mock_webpdf_exporter_instance++ result = exporter.export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=False, # Request standard PDF, but it should fall back+ )++ # Should fall back to webpdf and succeed+ assert result == b"fallback_webpdf_data"+ # PDFExporter was tried first+ mock_pdf_exporter.assert_called_once()+ mock_pdf_exporter_instance.from_notebook_node.assert_called_once()+ # WebPDFExporter was used as fallback+ mock_webpdf_exporter.assert_called_once()+ mock_webpdf_exporter_instance.from_notebook_node.assert_called_once()+ # Verify allow_chromium_download is set on fallback+ assert (+ mock_webpdf_exporter_instance.allow_chromium_download is True+ )