Wall-Safe Room Labels, Fixture-Tag Collision Avoidance, and Vector Door Geometry in pdf-lib (TypeScript)
Generating a CAD floor plan PDF with pdf-lib is easy on a single 24' × 18' open-concept studio. The moment a real user drafts a 48' × 34' three-bedroom house with two 5' × 8' bathrooms, a 3'-6" hallway, a 16'-0" overhead
Generating a CAD floor plan PDF with pdf-lib is easy on a single 24' × 18' open-concept studio. The moment a real user drafts a 48' × 34' three-bedroom house with two 5' × 8' bathrooms, a 3'-6" hallway, a 16'-0" overhead garage door, and kitchen cabinetry packed into every corner, naive PDF drawing code falls apart visually:
- Room names (
PRIMARY BATHROOM,10'-4" x 5'-2",53 SQ FT) spill straight across adjacent wall lines. - Small fixture codes (
WC,VAN,DW,RNG) collide directly on top of the room's centroid title block. - A
16'-0"wide garage bay renders with a comical16-foot hinged door swing arc slashing across the entire garage floor. - Standard
pdf-libbuilt-in fonts (Helvetica,Courier) throw a runtime encoding error if a user types a curly apostrophe, em dash, or Unicode fraction in a room name.
In PlanCaliber, our vector blueprint compiler (src/lib/cad/export-pdf.ts) generates five scaled 1/4" = 1'-0" sheets entirely in TypeScript with pdf-lib—zero headless Chrome, zero raster screenshots. Below are the exact deterministic typography and geometry safeguards that keep dense real-world plans readable at print scale.
1. Wall-Safe Room Labels with Exact widthOfTextAtSize Auto-Fitting
Instead of picking a fixed 8 pt font and hoping every closet or hallway is wide enough to hold three lines of text, we compute the room's actual printable clear box in PDF points using the active architectural scale factor s (points per real-world inch—for 1/4" = 1'-0", s = 18 / 12 = 1.5 pt/in):
const availW = Math.max(16, r.clearWidthIn * s - 5);
const availH = Math.max(10, r.clearLengthIn * s - 4);
From availW and availH, we progressively fit the room title, clear dimensions (12'-4" x 11'-0"), and square-footage line (136 SQ FT), shrinking font size down to a legible floor (4.0 pt bold / 3.6 pt mono) and automatically dropping secondary lines when a narrow 3'-6" hallway or 4' × 5' powder room simply lacks vertical room:
let nameSize = Math.min(8.5, Math.max(5.2, s * 5.2));
const rawW1 = fonts.sansBold.widthOfTextAtSize(titleStr, nameSize);
if (rawW1 > availW) {
nameSize = Math.max(4.0, nameSize * (availW / rawW1));
}
const fittedTitle = fitPdfText(titleStr, fonts.sansBold, nameSize, availW + 4);
let subSize = Math.min(6.8, Math.max(4.4, s * 4.0));
const maxRawSub = Math.max(
fonts.mono.widthOfTextAtSize(dimStr, subSize),
fonts.mono.widthOfTextAtSize(areaStr, subSize)
);
if (maxRawSub > availW) {
subSize = Math.max(3.6, subSize * (availW / maxRawSub));
}
const showDims =
availH >= subSize * 3.1 &&
fonts.mono.widthOfTextAtSize(dimStr, subSize) <= availW + 5;
const showArea =
availH >= subSize * 4.4 &&
fonts.mono.widthOfTextAtSize(areaStr, subSize) <= availW + 6;
Two details make a massive difference on printed paper:
-
Readability halo: Before drawing the text stack, we lay down an
84%-opaque white rectangle (opacity: 0.84) sized tightly around the active lines (boxW = Math.max(w1, w2, w3) + 5). Even if a dimension tick or dashed clearance line passes behind the room centroid, the label stays crisp and scannable without hiding floor fills underneath. -
WinAnsi text sanitization (
safePdfText): Standard PDF Type 1 fonts only support WinAnsi encoding. Sanitizing user-typed room titles (normalizing smart quotes, fractions, and non-Latin glyphs to clean ASCII before callingwidthOfTextAtSizeordrawText) guarantees that a user naming a roomChef’s Kitchen — 12½'never crashes PDF export.
2. Preventing Fixture Codes from Colliding with Room Centroids
Every cabinet, sink, toilet, range, and shower pan carries a compact architectural code (WC, LAV, SHW, RNG, REF). In a 12' × 14' kitchen, those tags sit cleanly near the perimeter walls. In a compact 5' × 8' bathroom, a 60" × 32" tub or centered vanity lands right on top of the room's geometric centroid—printing VAN straight through HALL BATH.
A fast two-part guard prevents both microscopic unreadable tags and centroid collisions:
const nearRoomLabel = rooms.some(
(r) => Math.hypot(fx.x - r.centroid.x, fx.y - r.centroid.y) < 16
);
if (
!opts.screened &&
!opts.solidBlackWalls &&
!nearRoomLabel &&
Math.min(fx.widthIn, fx.depthIn) * s >= 16
) {
const ctr = proj.toPdf(fx.x, fx.y);
const label = safePdfText(fx.code);
const fontSize = Math.min(6.2, Math.max(4.5, s * 3.4));
const tw = fonts.mono.widthOfTextAtSize(label, fontSize);
page.drawText(label, {
x: ctr.x - tw * 0.5,
y: ctr.y - fontSize * 0.35,
font: fonts.mono,
size: fontSize,
color: C_MUTED
});
}
Checking Math.hypot(fx.x - r.centroid.x, fx.y - r.centroid.y) < 16 (16 real-world inches) keeps the room name completely unobstructed in tight bathrooms and laundry closets, while Math.min(fx.widthIn, fx.depthIn) * s >= 16 suppresses unreadable micro-tags when zoomed out to 1/8" = 1'-0" on large barndominiums or commercial suites.
3. Clean Architectural Wall Breaks & Realistic Door Geometry
On a real architectural sheet, walls do not simply draw as continuous lines with doors stamped on top. Each wall is pre-split into full-height vertical piers (piece.bottomIn <= 0.5 && piece.topIn >= wallH - 0.5) so doorways and window rough openings break the wall poché cleanly down to the framing jambs.
For doors themselves, treating every door opening as a hinged quarter-circle swing creates a glaring visual bug on 9'-0" or 16'-0" garage bays. We branch explicitly on opening geometry:
- Windows: Crisp white jamb rectangle with a centered glazing line.
- Cased openings: Dashed header line along the wall face.
- Sliding / pocket / bifold doors: Dashed track line between jambs.
-
Overhead garage / wide bay doors (
widthIn >= 72 || swing === 'none'): Parallel double-dashed overhead panel lines inside the jamb thickness—never a giant swing arc:
if (op.kind === 'door' && (op.widthIn >= 72 || op.swing === 'none')) {
const offIn = Math.max(1.2, halfT * 0.45);
for (const sign of [1, -1]) {
page.drawLine({
start: proj.toPdf(j1.x + sw.normX * offIn * sign, j1.y + sw.normY * offIn * sign),
end: proj.toPdf(j2.x + sw.normX * offIn * sign, j2.y + sw.normY * offIn * sign),
thickness: opts.screened ? 0.65 : 1.05,
color: wallStroke,
dashArray: [5, 2.5]
});
}
continue;
}
- Hinged single & double doors: Exact door-leaf line extending perpendicular to the wall face plus a 12-segment dashed quarter-circle swing arc computed directly in real-world inches before projecting to PDF points:
const drawDoorLeafAndArc = (
hingeM: Point2D,
closedDir: Point2D,
radiusIn: number
): void => {
const openTipM = {
x: hingeM.x + sNorm.x * radiusIn,
y: hingeM.y + sNorm.y * radiusIn
};
page.drawLine({
start: proj.toPdf(hingeM.x, hingeM.y),
end: proj.toPdf(openTipM.x, openTipM.y),
thickness: opts.screened ? 0.6 : 1.15,
color: wallStroke
});
const steps = 12;
let prev = proj.toPdf(openTipM.x, openTipM.y);
for (let k = 1; k <= steps; k++) {
const t = (k / steps) * (Math.PI / 2);
const mx =
hingeM.x + (sNorm.x * Math.cos(t) + closedDir.x * Math.sin(t)) * radiusIn;
const my =
hingeM.y + (sNorm.y * Math.cos(t) + closedDir.y * Math.sin(t)) * radiusIn;
const cur = proj.toPdf(mx, my);
if (k % 2 === 1) {
page.drawLine({
start: prev,
end: cur,
thickness: 0.55,
color: opts.screened ? C_SCREENED : C_MUTED
});
}
prev = cur;
}
};
Because every arc vertex is computed in real-world model inches first and mapped through proj.toPdf(x, y) (which handles the Y-axis flip from screen/CAD coordinates to PDF bottom-left origin), single doors, French double doors, and 45-degree walls always produce mathematically true quarter-circle arcs that print accurately at 1/4" = 1'-0" on any scale ruler.
Inspecting Real Output
You can preview these exact vector sheets live in your browser across 20 residential, ADU, barndominium, and commercial layouts in PlanCaliber's template library or test the Blueprint & AutoCAD DXF studio directly with no account required.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.