Markdown to PDF - Live preview and export markdown as a PDF.
---
format: typebulb/v1
name: Markdown to PDF
---
**code.tsx**
```tsx
import React, { useState, useRef } from "react";
import { createRoot } from "react-dom/client";
import MarkdownIt from "markdown-it";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
const md = new MarkdownIt({
html: false,
breaks: false,
linkify: true,
typographer: true,
});
function deriveFilename(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") + ".pdf";
}
const DEFAULT_MARKDOWN = `# Markdown → PDF
A **live preview** PDF tool. Edit on the left, see the rendered output on the right, click *Download PDF* when ready.
## Features
- Live preview as you type
- A4 page layout
- Runs entirely in your browser
### Example
> "The best way to predict the future is to invent it." — Alan Kay
\`\`\`
const sum = (a: number, b: number) => a + b;
\`\`\`
| Item | Quantity |
|--------|----------|
| Coffee | 2 |
| Tea | 1 |
---
Edit this text to get started.
`;
const App = () => {
const [markdown, setMarkdown] = useState(DEFAULT_MARKDOWN);
const [fitOnePage, setFitOnePage] = useState(false);
const [exporting, setExporting] = useState(false);
const previewRef = useRef<HTMLDivElement>(null);
const html = md.render(markdown);
const handleExport = async () => {
if (!previewRef.current) return;
setExporting(true);
try {
const safeName = deriveFilename(markdown);
const canvas = await html2canvas(previewRef.current, {
scale: 2,
useCORS: true,
backgroundColor: "#ffffff",
windowWidth: 794,
onclone: (doc) => {
if (fitOnePage) {
// Strip min-height in fit mode so capture sizes to actual content,
// not padded out to a full A4 sheet.
const p = doc.querySelector(".page") as HTMLElement | null;
if (p) p.style.minHeight = "0";
}
},
});
const pdf = new jsPDF({ unit: "mm", format: "a4", orientation: "portrait" });
const pageW = pdf.internal.pageSize.getWidth();
const pageH = pdf.internal.pageSize.getHeight();
const margin = 15;
const contentW = pageW - 2 * margin;
const contentH = pageH - 2 * margin;
if (fitOnePage) {
// Single page: scale the entire captured canvas to fit, preserving aspect.
const canvasAR = canvas.height / canvas.width;
const contentAR = contentH / contentW;
let drawW: number;
let drawH: number;
if (canvasAR > contentAR) {
drawH = contentH;
drawW = contentH / canvasAR;
} else {
drawW = contentW;
drawH = contentW * canvasAR;
}
const dataUrl = canvas.toDataURL("image/jpeg", 0.95);
const x = margin + (contentW - drawW) / 2;
const y = margin + (contentH - drawH) / 2;
pdf.addImage(dataUrl, "JPEG", x, y, drawW, drawH);
} else {
// Multi-page: slice the captured canvas so each page carries only its own pixels.
const pxPerMm = canvas.width / contentW;
const pageHpx = contentH * pxPerMm;
let yOffset = 0;
let firstPage = true;
while (yOffset < canvas.height) {
if (!firstPage) pdf.addPage();
firstPage = false;
const sliceH = Math.min(pageHpx, canvas.height - yOffset);
const slice = document.createElement("canvas");
slice.width = canvas.width;
slice.height = sliceH;
const ctx = slice.getContext("2d")!;
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, slice.width, slice.height);
ctx.drawImage(canvas, 0, yOffset, canvas.width, sliceH, 0, 0, canvas.width, sliceH);
const sliceData = slice.toDataURL("image/jpeg", 0.95);
const sliceHmm = sliceH / pxPerMm;
pdf.addImage(sliceData, "JPEG", margin, margin, contentW, sliceHmm);
yOffset += pageHpx;
}
}
pdf.save(safeName);
} catch (err) {
console.error(err);
} finally {
setExporting(false);
}
};
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 download files. 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">
<header className="bar">
<h1>Markdown → PDF</h1>
<div className="bar-actions">
<label className="toggle">
<input
type="checkbox"
checked={fitOnePage}
onChange={(e) => setFitOnePage(e.target.checked)}
/>
<span>Fit on one page</span>
</label>
<button className="primary-btn" onClick={handleExport} disabled={exporting}>
{exporting ? "Generating..." : "Download PDF"}
</button>
</div>
</header>
<div className="workspace">
<textarea
className="editor"
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
spellCheck={false}
/>
<div className="preview-scroll">
<div
className="page"
ref={previewRef}
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.875rem 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;
}
.primary-btn {
background: var(--accent);
color: var(--card-bg);
border: 1px solid var(--accent);
padding: 0.5rem 1.1rem;
border-radius: 8px;
font-weight: 600;
font-size: 0.875rem;
cursor: pointer;
transition: opacity 0.2s;
letter-spacing: -0.01em;
}
.primary-btn:hover { opacity: 0.9; }
.primary-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.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: 1fr 1fr;
flex: 1;
min-height: 0;
}
.editor {
border: none;
outline: none;
resize: none;
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);
}
.preview-scroll {
overflow: auto;
background: var(--bg);
padding: 2rem;
}
/* The "page" — styled to look like a printed A4 sheet at 96dpi. */
.page {
background: #ffffff;
color: #1d1d1f;
width: 794px;
min-height: 1123px;
margin: 0 auto;
padding: 60px;
box-shadow: var(--shadow-lg);
font-family: "Georgia", "Times New Roman", serif;
font-size: 11pt;
line-height: 1.55;
}
.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;
}
.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;
}
.editor {
border-right: none;
border-bottom: 1px solid var(--border);
min-height: 40vh;
}
.bar h1 { font-size: 1rem; }
}
@media (max-width: 600px) {
.bar {
padding: 0.75rem 1rem;
padding-right: 5rem;
}
}
```
**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",
"jspdf": "^2.5.2",
"html2canvas": "^1.4.1"
},
"description": "Markdown to PDF - Live preview and export markdown as a PDF."
}
```