# Client-Side PDF Floor-Plan Rasterization & Vision Input Normalization in TypeScript (Zero Server Poppler or Ghostscript)

When users import an existing house blueprint, landlord leasing brochure, or scanned builder sheet into a browser CAD editor, roughly half of those files are not PNGs or JPEGs—they are **PDFs**. Sometimes it is a crisp vector `ARCH D` (`24" × 36"`) drawing exported from Revit; other times it is a scanned `8.5" × 11"` broker flyer with transparent linework over an unpainted background.

If your backend runs on edge isolates (such as Cloudflare Workers) with tight memory ceilings and no native `poppler`, `pdfium`, or `Ghostscript` binaries, rasterizing arbitrary multi-megabyte architectural PDFs on the server is a non-starter. Even on a containerized Node backend, untrusted PDF decoding is slow, memory-hungry, and expensive to scale.

In [PlanCaliber](https://www.plancaliber.com/pdf-to-cad-floor-plan), we moved the entire PDF and smartphone-photo normalization pipeline into the browser in ~65 lines of TypeScript—keeping the initial app bundle completely free of PDF decoding weight while handing our edge API clean, bounded, white-backed JPEGs every time.

Here are the five concrete failure modes we hit in production and the exact TypeScript patterns that fixed them.

---

## 1. Zero Initial Bundle Cost via Lazy `pdfjs-dist` + Vite `?url` Worker Loading

`pdfjs-dist` and its web worker are large. Users who land in a floor plan editor to draw walls from scratch or load a template should never download a PDF rendering engine on first paint.

Instead of importing `pdfjs-dist` at module top level, we dynamically import both the library and its Vite-resolved worker asset URL inside the upload handler only when `file.type === 'application/pdf'` or the filename ends in `.pdf`:

```ts
async function pdfFileToNormalizedDataUrl(
	file: File
): Promise<{ dataUrl: string; base64: string }> {
	const [pdfjs, workerUrlMod] = await Promise.all([
		import('pdfjs-dist'),
		import('pdfjs-dist/build/pdf.worker.min.mjs?url')
	]);
	pdfjs.GlobalWorkerOptions.workerSrc = workerUrlMod.default;

	const buf = await file.arrayBuffer();
	const loadingTask = pdfjs.getDocument({ data: new Uint8Array(buf) });
	const pdf = await loadingTask.promise;
	const page = await pdf.getPage(1);
```

Using `pdfjs-dist/build/pdf.worker.min.mjs?url` tells Vite to emit the worker as a fingerprinted static asset served from our own origin—avoiding flaky third-party CDN worker URLs, version mismatches between main thread and worker, and Content-Security-Policy worker blocks.

---

## 2. Adaptive Scale Clamping: Why Fixed `scale: 2` Breaks on Both `ARCH D` and Letter Scans

A common tutorial mistake with `pdf.js` is hardcoding `page.getViewport({ scale: 2 })` or `scale: 3`. On architectural sheets, PDF page dimensions vary wildly in PDF points (`72 pt = 1 inch`):

| Sheet Type | Physical Size | PDF Point Size (`scale: 1`) | Fixed `scale: 3` Canvas | Adaptive `2000px` Clamp |
|---|---|---|---|---|
| US Letter flyer | `8.5" × 11"` | `612 × 792 pt` | `1836 × 2376 px` | `1545 × 2000 px` (`scale = 2.53`) |
| Tabloid / Ledger | `11" × 17"` | `792 × 1224 pt` | `2376 × 3672 px` | `1294 × 2000 px` (`scale = 1.63`) |
| `ARCH D` blueprint | `24" × 36"` | `1728 × 2592 pt` | **`5184 × 7776 px` (~161 MB RGBA!)** | `2074 × 3110 px` (`scale = 1.20`) |
| Small cropped sketch | `4" × 5"` | `288 × 360 pt` | `864 × 1080 px` | `864 × 1080 px` (`scale = 3.00`) |

A `5184 × 7776` RGBA canvas consumes over **160 MB of uncompressed backing memory** on a single page—enough to crash mobile Safari or trigger a canvas allocation failure before `toDataURL()` even runs. Conversely, scaling a tiny broker thumbnail down to `scale: 1` turns `10'-6"` dimension strings into unreadable gray smudges.

The fix is a single bounded scale expression targeting a `2000 px` long edge, clamped between `1.2` and `3.0`:

```ts
	const baseVp = page.getViewport({ scale: 1 });
	const targetScale = Math.min(
		3,
		Math.max(1.2, 2000 / Math.max(baseVp.width, baseVp.height, 1))
	);
	const viewport = page.getViewport({ scale: targetScale });

	const c = document.createElement('canvas');
	c.width = Math.max(1, Math.round(viewport.width));
	c.height = Math.max(1, Math.round(viewport.height));
	const ctx = c.getContext('2d');
	if (!ctx) throw new Error('Could not initialize canvas for PDF rendering.');
```

Every `8.5" × 11"` scan gets enough resolution (`~2000 px` tall) to preserve hairline wall ticks and `1/4"` dimension callouts, while `ARCH D` sheets stay safely inside browser canvas memory limits.

---

## 3. The Transparent Vector PDF Trap (Why Your Exported JPEG Turns Pitch-Black)

Many CAD exporters (AutoCAD, Revit, Chief Architect, Vectorworks) emit PDF pages with **no white background rectangle**—just black vector strokes drawn over an alpha-transparent canvas.

If you render that page onto a fresh `<canvas>` and immediately call `canvas.toDataURL('image/jpeg', 0.9)`, JPEG has no alpha channel. Transparent pixels (`rgba(0,0,0,0)`) flatten straight to `#000000` black—producing black blueprint lines on a solid black sheet.

Always fill an explicit `#FFFFFF` paper backdrop *before* calling `page.render()`, and explicitly destroy the PDF loading task afterward so the decoded font and stream buffers are released immediately:

```ts
	ctx.fillStyle = '#FFFFFF';
	ctx.fillRect(0, 0, c.width, c.height);
	await page.render({ canvasContext: ctx, canvas: c, viewport }).promise;

	const jpegUrl = c.toDataURL('image/jpeg', 0.9);
	await loadingTask.destroy().catch(() => {});
	return { dataUrl: jpegUrl, base64: jpegUrl.split(',')[1] ?? '' };
}
```

That same `#FFFFFF` pre-fill is equally critical for uploaded transparent PNG floor plans (common from real estate marketing sites and dark-mode CAD screenshots).

---

## 4. Normalizing 12-Megapixel Smartphone Photos Before They Hit the Wire

A modern phone photo of a hand-drawn graph-paper sketch easily runs `4032 × 3024` pixels and `5–8 MB`. Sending that raw payload to an edge function wastes upload latency, risks tripping body-size ceilings, and gives a vision digitizer zero extra geometric accuracy over a clean `1536 px` raster.

Our unified `fileToNormalizedDataUrl()` branches on PDF vs. raster images and runs every non-PDF upload through the same white-backed canvas normalizer (`maxDim = 1536`, JPEG `0.84`):

```ts
async function fileToNormalizedDataUrl(
	file: File
): Promise<{ dataUrl: string; base64: string }> {
	if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) {
		return pdfFileToNormalizedDataUrl(file);
	}
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onerror = () => reject(new Error('Failed to read image file.'));
		reader.onload = () => {
			const rawDataUrl = String(reader.result ?? '');
			const img = new Image();
			img.onerror = () =>
				reject(new Error('Unsupported image format. Use PNG, JPG, or WEBP.'));
			img.onload = () => {
				const maxDim = 1536;
				const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
				const w = Math.max(1, Math.round(img.width * scale));
				const h = Math.max(1, Math.round(img.height * scale));
				const c = document.createElement('canvas');
				c.width = w;
				c.height = h;
				const ctx = c.getContext('2d');
				if (!ctx) {
					const comma = rawDataUrl.indexOf(',');
					resolve({
						dataUrl: rawDataUrl,
						base64: comma >= 0 ? rawDataUrl.slice(comma + 1) : rawDataUrl
					});
					return;
				}
				ctx.fillStyle = '#FFFFFF';
				ctx.fillRect(0, 0, w, h);
				ctx.drawImage(img, 0, 0, w, h);
				const jpegUrl = c.toDataURL('image/jpeg', 0.84);
				resolve({ dataUrl: jpegUrl, base64: jpegUrl.split(',')[1] ?? '' });
			};
			img.src = rawDataUrl;
		};
		reader.readAsDataURL(file);
	});
}
```

A `6.4 MB` iPhone sketch photo compresses down to `~180–260 KB` in under `80 ms` on-device, and the exact same `dataUrl` doubles as a translucent `0.16`-opacity underlay inside the 2D CAD viewport so the user can visually audit traced walls against their original scan.

---

## 5. Server-Side Guardrails: 3-Way Classification & Clean Title-Block Filenames

Even with well-behaved client normalization, the edge API enforces a hard `6 MB` byte cap and treats every incoming image through a strict three-way union contract rather than blindly hallucinating walls on every upload:

```ts
export type VisionParseResponse =
	| {
			status: 'ok';
			plan: PlanDocument;
			solved: SolvedPlan;
			suggestedCalibrationWallId?: string;
			readDimensionInches?: number;
	  }
	| {
			status: 'needs_dimensions';
			detectedRoomType: RoomType;
			detectedSummary: string;
			suggestedWidthFt: number;
			suggestedDepthFt: number;
	  }
	| {
			status: 'error';
			detail: string;
	  };
```

- **`floor_plan`**: top-down sketches, blueprints, and broker diagrams proceed through deterministic wall-graph healing, room-cycle solving, and scale normalization.
- **`eye_level_photo`**: if a user accidentally snaps a perspective photo of their kitchen instead of a top-down diagram, we refuse to fabricate fake walls—returning `needs_dimensions` with the detected room type and suggested feet so they can generate a clean rectangular room shell in one click.
- **`unrelated`**: rejected cleanly with a clear error message.

Finally, one tiny polish detail that makes a huge difference on printed PDF title blocks: users constantly upload files named `IMG_6140.jpg`, `Screenshot 2026-11-25 at 11.03.54 PM.png`, or `9f3a2c10-8b2d-4c11.pdf`. Passing the raw filename straight into the drawing title puts `"IMG_6140"` in the architectural title block. A deterministic regex filter keeps meaningful project names (like `Maple St ADU Ground Floor`) while substituting the semantic title extracted from the drawing whenever the filename looks like a camera dump or UUID:

```ts
export function pickCleanSketchTitle(hintTitle: string, parsedTitle: unknown): string {
	const cleanedAi = typeof parsedTitle === 'string' ? parsedTitle.trim().slice(0, 120) : '';
	const cleanedHint = hintTitle.trim().slice(0, 120);
	const isGenericCameraName =
		!cleanedHint ||
		/^(img|image|dsc|dcim|pxl|photo|pic|picture|scan|screenshot|screen[\s_-]?shot|whatsapp[\s_-]?image|capture|download|untitled|file|doc|document|phone[\s_-]?sketch)([\s_-]|\d|\(|$)/i.test(
			cleanedHint
		) ||
		/^(my[\s_-]?)?(floor[\s_-]?plan|sketch|plan|blueprint|layout|house|home|room)([\s_-]*\d+)?$/i.test(
			cleanedHint
		) ||
		/^[\d\s._-]+$/.test(cleanedHint) ||
		/^[0-9a-f]{8}[-_]?[0-9a-f]{4}/i.test(cleanedHint);
	if (!isGenericCameraName) return cleanedHint;
	if (cleanedAi) return cleanedAi;
	return 'Custom Floor Plan';
}
```

---

## Try the Pipeline Live

You can test the client-side PDF and sketch rasterizer directly in the browser—no signup required—on the [PlanCaliber PDF-to-CAD converter](https://www.plancaliber.com/pdf-to-cad-floor-plan) or drop any sketch straight into the [2D/3D CAD Studio](https://www.plancaliber.com/?intent=sketch). Every uploaded scan stays paired with 1-wall scale calibration, deterministic planar room solving, and clean `1/4" = 1'-0"` vector PDF / layered AutoCAD R12 `.DXF` export.
