Markdown to PDF

Markdown to PDF - Live preview and export markdown as a PDF.

code.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 />);

Markdown source · More bulbs by samples · Typebulb home