---
format: typebulb/v1
name: Markdown to PDF
---

**code.tsx**

```tsx
import React, { useState, useRef, useEffect } from "react";
import { createRoot } from "react-dom/client";
import MarkdownIt from "markdown-it";
import { tasklist } from "@mdit/plugin-tasklist";
import { footnote } from "@mdit/plugin-footnote";
import hljs from "highlight.js/lib/common";

const md = new MarkdownIt({
  html: true,
  breaks: false,
  linkify: true,
  typographer: true,
  // Only tagged fences are highlighted: auto-detect would run every grammar on each keystroke.
  highlight: (code: string, lang: string) =>
    lang && hljs.getLanguage(lang) ? hljs.highlight(code, { language: lang }).value : "",
})
  .use(tasklist)
  .use(footnote);

type PageSize = "a4" | "letter";
const PAGE_MM: Record<PageSize, { label: string; w: number; h: number }> = {
  a4: { label: "A4", w: 210, h: 297 },
  letter: { label: "Letter", w: 215.9, h: 279.4 },
};
const MARGIN_MM = 15;
const PX_PER_MM = 96 / 25.4;

// The H1's slug names the file: the browser's Save-as-PDF takes the tab title.
function deriveTitle(markdown: string): string {
  const match = markdown.match(/^#\s+(.+)$/m);
  const raw = match ? match[1] : "";
  const slug = raw
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .trim()
    .replace(/\s+/g, "-")
    .slice(0, 60);
  return slug || "document";
}

const DRAFT_KEY = "markdown-to-pdf.draft";
const SPLIT_KEY = "markdown-to-pdf.split";
// Storage throws in the inline sandbox and some private modes: persistence is best-effort.
function readStored(key: string): string {
  try { return localStorage.getItem(key) || ""; } catch { return ""; }
}
function writeStored(key: string, value: string) {
  try { localStorage.setItem(key, value); } catch {}
}

const DEFAULT_MARKDOWN = `# Markdown → PDF

A **live preview** PDF tool. Edit on the left, see the rendered output on the right, click the download button when ready.

## Features

- Live preview as you type
- A4 or Letter pages, with real text and clickable links in the PDF
- Syntax-highlighted code blocks, task lists and footnotes[^1]
- Runs entirely in your browser: nothing is uploaded

### Example

> "The best way to predict the future is to invent it." — Alan Kay

\`\`\`ts
const sum = (a: number, b: number) => a + b;
\`\`\`

| Item   | Quantity |
|--------|----------|
| Coffee | 2        |
| Tea    | 1        |

- [x] Write the document
- [ ] Download the PDF

---

Need a page break? Insert \`<div style="break-after: page"></div>\` where the next page should start.

Edit this text to get started, or drop a .md file onto the editor.

[^1]: Like this one.
`;

const App = () => {
  const [markdown, setMarkdown] = useState(() => readStored(DRAFT_KEY) || DEFAULT_MARKDOWN);
  const [split, setSplit] = useState(() => Number(readStored(SPLIT_KEY)) || 0.5); // the editor's share of the width
  const [fitOnePage, setFitOnePage] = useState(false);
  const [pageSize, setPageSize] = useState<PageSize>("a4");
  const previewRef = useRef<HTMLDivElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const workspaceRef = useRef<HTMLDivElement>(null);
  const paneRef = useRef<HTMLDivElement>(null);
  const [paneWidth, setPaneWidth] = useState(0);

  useEffect(() => writeStored(DRAFT_KEY, markdown), [markdown]);
  useEffect(() => writeStored(SPLIT_KEY, String(split)), [split]);
  useEffect(() => {
    const ro = new ResizeObserver(([entry]) => setPaneWidth(entry.contentRect.width));
    ro.observe(paneRef.current!);
    return () => ro.disconnect();
  }, []);

  const html = md.render(markdown);
  const page = PAGE_MM[pageSize];
  // Fit-to-width: the sheet keeps its real layout width and is only rendered scaled (CSS zoom),
  // so line breaks match the PDF whatever the pane's width.
  const previewZoom = paneWidth ? paneWidth / (page.w * PX_PER_MM) : 1;

  const openFile = async (file: File | undefined) => {
    if (file) setMarkdown(await file.text());
  };

  const onSplitDown = (e: React.PointerEvent<HTMLDivElement>) => {
    e.preventDefault();
    const handle = e.currentTarget;
    const box = workspaceRef.current!.getBoundingClientRect();
    const rows = handle.offsetWidth > handle.offsetHeight; // stacked layout: the handle is a row
    handle.setPointerCapture(e.pointerId);
    const onMove = (pe: PointerEvent) => {
      const t = rows ? (pe.clientY - box.top) / box.height : (pe.clientX - box.left) / box.width;
      setSplit(Math.min(0.8, Math.max(0.2, t)));
    };
    const onUp = () => {
      handle.removeEventListener("pointermove", onMove);
      handle.removeEventListener("pointerup", onUp);
      handle.removeEventListener("pointercancel", onUp);
      document.body.style.cursor = "";
    };
    document.body.style.cursor = rows ? "row-resize" : "col-resize";
    handle.addEventListener("pointermove", onMove);
    handle.addEventListener("pointerup", onUp);
    handle.addEventListener("pointercancel", onUp);
  };

  // The browser's own HTML-to-PDF engine does the conversion; the print CSS hides everything but the sheet.
  const handleDownload = () => {
    const preview = previewRef.current;
    if (!preview) return;
    let zoom = 1;
    if (fitOnePage) {
      // Uniform zoom so the sheet's printed height fits one page's printable area. scrollHeight is
      // in the sheet's own CSS px whatever the preview zoom (rects aren't, across Chromium versions).
      const contentH = preview.scrollHeight - 2 * MARGIN_MM * PX_PER_MM;
      const printableH = (page.h - 2 * MARGIN_MM) * PX_PER_MM;
      if (contentH > printableH) zoom = (printableH / contentH) * 0.99;
    }
    document.documentElement.style.setProperty("--print-zoom", String(zoom));
    const prevTitle = document.title;
    document.title = deriveTitle(markdown);
    window.addEventListener("afterprint", () => { document.title = prevTitle; }, { once: true });
    window.print();
  };

  const ua = navigator.userAgent;
  const isWebView = (/iPhone|iPad|iPod/i.test(ua) && !ua.includes('Safari')) || /; wv\)/.test(ua);

  if (isWebView) return (
    <div className="app">
      <div className="in-app-banner">
        Your in-app browser can't save PDFs. Please open this page directly in your browser.
        <button className="copy-link-btn" onClick={async () => tb.copy(await tb.url())}>
          Copy Link
        </button>
      </div>
    </div>
  );

  return (
    <div
      className="app"
      style={{
        "--page-w": `${page.w}mm`,
        "--page-h": `${page.h}mm`,
        "--margin": `${MARGIN_MM}mm`,
        "--preview-zoom": previewZoom,
      } as React.CSSProperties}
    >
      <style>{`@page { size: ${page.w}mm ${page.h}mm; margin: ${MARGIN_MM}mm; }`}</style>
      <header className="bar">
        <h1>Markdown → PDF</h1>
        <div className="bar-actions">
          <input
            ref={fileRef}
            type="file"
            accept=".md,.markdown,.txt,text/markdown,text/plain"
            hidden
            onChange={(e) => { openFile(e.target.files?.[0]); e.target.value = ""; }}
          />
          <button
            className="icon-btn"
            onClick={() => fileRef.current?.click()}
            aria-label="Open file"
            title="Open a markdown file"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
              strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
            </svg>
          </button>
          <select
            className="page-size"
            aria-label="Page size"
            value={pageSize}
            onChange={(e) => setPageSize(e.target.value as PageSize)}
          >
            {(Object.keys(PAGE_MM) as PageSize[]).map((k) => (
              <option key={k} value={k}>{PAGE_MM[k].label}</option>
            ))}
          </select>
          <label className="toggle">
            <input
              type="checkbox"
              checked={fitOnePage}
              onChange={(e) => setFitOnePage(e.target.checked)}
            />
            <span>Fit on one page</span>
          </label>
          <button
            className="icon-btn"
            onClick={handleDownload}
            aria-label="Download PDF"
            title="Download PDF"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
              strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M12 3v12" />
              <path d="m7 10 5 5 5-5" />
              <path d="M5 21h14" />
            </svg>
          </button>
        </div>
      </header>

      <div
        className="workspace"
        ref={workspaceRef}
        style={{ "--split-l": `${split}fr`, "--split-r": `${1 - split}fr` } as React.CSSProperties}
      >
        <textarea
          className="editor"
          value={markdown}
          onChange={(e) => setMarkdown(e.target.value)}
          onDragOver={(e) => e.preventDefault()}
          onDrop={(e) => { e.preventDefault(); openFile(e.dataTransfer.files[0]); }}
          spellCheck={false}
        />
        <div
          className="splitter"
          role="separator"
          aria-label="Resize panes"
          onPointerDown={onSplitDown}
        />
        <div className="preview-scroll" ref={paneRef}>
          <div
            className="page"
            ref={previewRef}
            role="region"
            aria-label="Preview"
            dangerouslySetInnerHTML={{ __html: html }}
          />
        </div>
      </div>
    </div>
  );
};

const container = document.getElementById("root");
const root = createRoot(container!);
root.render(<App />);
```
**styles.css**

```css
:root {
  --bg: #fafafa;
  --text: #1d1d1f;
  --text-muted: #6e6e73;
  --border: rgba(0, 0, 0, 0.1);
  --card-bg: #ffffff;
  --selection: rgba(0, 0, 0, 0.05);
  --accent: #1d1d1f;
  --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.06);
  --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.08);
  --shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.12);
}

html[data-theme="dark"] {
  --bg: #1c1c1c;
  --text: #f5f5f7;
  --text-muted: #a1a1a6;
  --border: rgba(255, 255, 255, 0.1);
  --card-bg: #232323;
  --selection: rgba(255, 255, 255, 0.08);
  --accent: #f5f5f7;
  --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.4);
  --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.5);
  --shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.6);
}

* { box-sizing: border-box; }

html, body, #root {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background: var(--bg);
  color: var(--text);
  font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.app {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.bar {
  display: flex;
  align-items: center;
  padding: 0.5rem 1.5rem;
  /* Leave room on the right for the Typebulb "Edit" overlay; keep all controls left. */
  padding-right: 9rem;
  border-bottom: 1px solid var(--border);
  background: var(--bg);
  flex-shrink: 0;
  gap: 1rem;
  flex-wrap: wrap;
}

.bar h1 {
  font-size: 1.125rem;
  font-weight: 700;
  margin: 0;
  letter-spacing: -0.02em;
}

.bar-actions {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  flex-wrap: wrap;
}

.icon-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  background: var(--card-bg);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
  transition: box-shadow 0.2s;
}

.icon-btn:hover { box-shadow: var(--shadow-sm); }

.page-size {
  height: 32px;
  padding: 0 0.5rem;
  font: inherit;
  font-size: 0.875rem;
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
}

.page-size, .page-size option { background: Canvas; color: CanvasText; }

.toggle {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.875rem;
  color: var(--text);
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
}

.toggle input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
  cursor: pointer;
  accent-color: var(--accent);
}

.workspace {
  display: grid;
  grid-template-columns: var(--split-l, 1fr) 6px var(--split-r, 1fr);
  flex: 1;
  min-height: 0;
}

.editor {
  border: none;
  outline: none;
  resize: none;
  min-width: 0;
  min-height: 0;
  padding: 1.5rem;
  font-family: "SF Mono", "Menlo", "Consolas", "Courier New", monospace;
  font-size: 0.875rem;
  line-height: 1.6;
  background: var(--card-bg);
  color: var(--text);
  border-right: 1px solid var(--border);
}

.splitter { cursor: col-resize; touch-action: none; }
.splitter:hover { background: var(--border); }

.preview-scroll {
  overflow: auto;
  overflow-y: scroll;   /* always present, so the fit zoom can't oscillate with the scrollbar */
  background: var(--bg);
  padding: 0;
}

/* The "page": a sheet at the chosen size, padded by the print margin so lines wrap where they will print. */
.page {
  background: #ffffff;
  color: #1d1d1f;
  width: var(--page-w);
  min-height: var(--page-h);
  margin: 0 auto;
  padding: var(--margin);
  box-shadow: var(--shadow-lg);
  font-family: "Georgia", "Times New Roman", serif;
  font-size: 11pt;
  line-height: 1.55;
  zoom: var(--preview-zoom, 1);
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}

.page > *:first-child { margin-top: 0; }
.page > *:last-child { margin-bottom: 0; }

.page h1, .page h2, .page h3, .page h4, .page h5, .page h6 {
  font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", sans-serif;
  font-weight: 700;
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  line-height: 1.2;
  letter-spacing: -0.02em;
  color: #1d1d1f;
}

.page h1 {
  font-size: 2em;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.3em;
}

.page h2 { font-size: 1.5em; }
.page h3 { font-size: 1.25em; }
.page h4 { font-size: 1.1em; }
.page h5 { font-size: 1em; }
.page h6 { font-size: 0.9em; color: #555; }

.page p { margin: 0.75em 0; }

.page code {
  background: #f3f3f3;
  padding: 0.12em 0.4em;
  border-radius: 4px;
  font-family: "SF Mono", "Menlo", "Consolas", "Courier New", monospace;
  font-size: 0.92em;
}

.page pre {
  background: #f5f5f5;
  padding: 1em;
  border-radius: 6px;
  overflow-x: auto;
  font-family: "SF Mono", "Menlo", "Consolas", "Courier New", monospace;
  font-size: 0.9em;
  line-height: 1.45;
  margin: 1em 0;
}

.page pre code {
  background: none;
  padding: 0;
  font-size: inherit;
}

.page blockquote {
  margin: 1em 0;
  padding: 0.4em 1em;
  border-left: 4px solid #ddd;
  color: #555;
  font-style: italic;
}

.page blockquote p { margin: 0.4em 0; }

.page table {
  border-collapse: collapse;
  width: 100%;
  margin: 1em 0;
  font-size: 0.95em;
}

.page th, .page td {
  border: 1px solid #ddd;
  padding: 0.5em 0.75em;
  text-align: left;
}

.page th {
  background: #f9f9f9;
  font-weight: 600;
}

.page ul, .page ol {
  margin: 0.75em 0;
  padding-left: 1.6em;
}

.page li { margin: 0.25em 0; }

.page a {
  color: #0066cc;
  text-decoration: underline;
}

.page hr {
  border: none;
  border-top: 1px solid #ddd;
  margin: 2em 0;
}

.page img {
  max-width: 100%;
  height: auto;
}

.page .task-list-container { list-style: none; padding-left: 0.4em; }
.page .task-list-item-checkbox { margin: 0 0.5em 0 0; vertical-align: -0.1em; }

.page .footnotes { font-size: 0.85em; color: #555; }
.page .footnote-ref a, .page .footnote-backref { text-decoration: none; }

/* A manual page break (<div style="break-after: page">) shows as a dashed rule in the preview. */
.page div[style*="break-after"] { border-top: 1px dashed #bbb; margin: 1.5em 0; }

/* highlight.js spans, GitHub-light tones (the sheet is always light). */
.hljs-comment, .hljs-quote { color: #6a737d; font-style: italic; }
.hljs-keyword, .hljs-selector-tag, .hljs-doctag, .hljs-meta { color: #d73a49; }
.hljs-string, .hljs-regexp, .hljs-addition { color: #032f62; }
.hljs-number, .hljs-literal, .hljs-symbol, .hljs-bullet, .hljs-attr { color: #005cc5; }
.hljs-title, .hljs-section, .hljs-name, .hljs-type, .hljs-built_in { color: #6f42c1; }
.hljs-variable, .hljs-template-variable, .hljs-attribute { color: #e36209; }
.hljs-deletion { color: #b31d28; }
.hljs-strong { font-weight: 600; }
.hljs-emphasis { font-style: italic; }

.in-app-banner {
  background: var(--selection);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 1rem 1.25rem;
  margin: 1.5rem;
  font-size: 0.875rem;
  color: var(--text);
  line-height: 1.5;
  text-align: center;
}

.copy-link-btn {
  display: block;
  margin: 0.75rem auto 0;
  padding: 0.5rem 1rem;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  background: var(--bg);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 8px;
  transition: box-shadow 0.2s;
}

.copy-link-btn:hover { box-shadow: var(--shadow-sm); }

@media (max-width: 900px) {
  .workspace {
    grid-template-columns: 1fr;
    grid-template-rows: var(--split-l, 1fr) 10px var(--split-r, 1fr);
  }
  .splitter { cursor: row-resize; }
  .editor {
    border-right: none;
    border-bottom: 1px solid var(--border);
  }
  .bar h1 { font-size: 1rem; }
}

@media (max-width: 600px) {
  .bar {
    padding: 0.5rem 1rem;
    padding-right: 5rem;
  }
}

@media print {
  html, body, #root, .app, .workspace, .preview-scroll {
    display: block;
    height: auto;
    overflow: visible;
  }
  body { background: #fff; }
  .bar, .editor, .splitter { display: none; }
  .preview-scroll { padding: 0; background: none; }
  .page {
    width: calc(var(--page-w) - 2 * var(--margin));
    min-height: 0;
    margin: 0 auto;
    padding: 0;
    box-shadow: none;
    zoom: var(--print-zoom, 1);   /* "Fit on one page": set by the download handler */
  }
  .page h1, .page h2, .page h3, .page h4, .page h5, .page h6 { break-after: avoid; }
  .page pre, .page tr, .page img, .page blockquote { break-inside: avoid; }
  .page div[style*="break-after"] { border: none; margin: 0; }
}
```
**index.html**

```html
<div id="root"></div>
```
**config.json**

```json
{
  "dependencies": {
    "react": "^19.2.3",
    "react-dom": "^19.2.3",
    "markdown-it": "^14.1.0",
    "@mdit/plugin-tasklist": "^1.1.0",
    "@mdit/plugin-footnote": "^1.1.0",
    "highlight.js": "^11.12.0"
  },
  "description": "Markdown to PDF - Live preview and export markdown as a PDF."
}
```