DEV Community

Felix Marlowe
Felix Marlowe

Posted on

Generating Deterministic 7-Layer AutoCAD R12 DXF Files in Zero-Dependency TypeScript on Cloudflare Workers

When engineering web applications export CAD drawings, developers often reach for heavyweight native C++ bindings (LibreDWG, OpenCascade), headless LibreCAD containers, or SVG-to-DXF CLI wrappers. None of those run inside a serverless edge isolate like Cloudflare Workers (where you have pure JavaScript/WebAssembly, strict CPU/memory caps, and zero local filesystem binaries).

If your goal is to produce clean, architect-grade 2D .DXF files that open cleanly in AutoCAD, BricsCAD, QCAD, Vectorworks, and Bluebeam Revu, you do not need any native dependencies. Generating AutoCAD R12 ASCII DXF (AC1009) directly from pure TypeScript takes fewer than 350 lines of deterministic code, executes in under 2 milliseconds at the edge, and avoids the brittle handle/class-dictionary validation errors that break newer R2000+ DXF generators.

Why Target R12 (AC1009) Instead of R2018?

AutoCAD R2000 through R2018 DXF files require a strict CLASSES section, unique hexadecimal HANDLE (5) IDs on every object, OWNER (330) parent pointers, BLOCK_RECORD entries, and an OBJECTS dictionary. One missing handle causes AutoCAD to abort loading the entire drawing with a generic syntax error.

AutoCAD R12 (AC1009) is the universal interchange baseline across the AEC industry:

  • Every modern CAD suite (AutoCAD 2026, Civil 3D, Vectorworks, Revit import, QCAD, Rhino) imports R12 ASCII natively.
  • It requires no CLASSES, no OBJECTS dictionary, and no handle graph.
  • Coordinates are exact double-precision floats in real-world architectural units (1 drawing unit = 1 inch, matching 1:1 US architectural model space).

Anatomy of a Valid R12 DXF File

An ASCII DXF file is strictly a sequence of group code / value pairs, separated by CRLF (\r\n). Every section begins with 0 / SECTION and 2 / <NAME>, and closes with 0 / ENDSEC. The file terminates with 0 / EOF.

type DxfPair = [code: number, value: string | number];

function serializePairs(pairs: DxfPair[]): string {
  const out: string[] = [];
  for (const [code, val] of pairs) {
    out.push(String(code).padStart(3, ' '));
    out.push(typeof val === 'number' ? formatNum(val) : sanitizeText(val));
  }
  return out.join('\r\n') + '\r\n';
}

function formatNum(n: number): string {
  // Deterministic rounding avoids -0.0000 and noisy IEEE-754 tails
  const rounded = Math.abs(n) < 1e-6 ? 0 : Math.round(n * 10000) / 10000;
  return rounded.toFixed(4);
}

function sanitizeText(s: string): string {
  // Strip control characters and CR/LF that would corrupt DXF group alignment
  return s.replace(/[\r\n\t]+/g, ' ').replace(/[^\x20-\x7E]/g, '');
}
Enter fullscreen mode Exit fullscreen mode

Notice sanitizeText: never interpolate unescaped user text into a DXF stream. A single newline (\n) inside a room title or furniture label shifts every subsequent group code by one line and corrupts the file completely.

Defining AIA-Style Semantic Layers in TABLES

Architects and fire protection engineers immediately judge a .DXF file by its layer table. Dumping geometry onto layer 0 forces manual cleanup. Define explicit named layers in the TABLES section using standard AutoCAD Color Index (ACI) integers (1 = red, 2 = yellow, 3 = green, 4 = cyan, 7 = white/black, 8 = gray):

export interface CadLayer {
  name: string;
  aciColor: number;
  lineType: 'CONTINUOUS' | 'DASHED';
}

export const ARCHITECTURAL_LAYERS: CadLayer[] = [
  { name: 'A-WALL-PERIM', aciColor: 7, lineType: 'CONTINUOUS' },
  { name: 'A-DOOR-EGRESS', aciColor: 3, lineType: 'CONTINUOUS' },
  { name: 'A-FURN-LAYOUT', aciColor: 8, lineType: 'CONTINUOUS' },
  { name: 'F-LIFE-SAFETY', aciColor: 1, lineType: 'CONTINUOUS' },
  { name: 'F-EXTG-RADIUS', aciColor: 1, lineType: 'DASHED' },
  { name: 'A-ANNO-DIMS', aciColor: 4, lineType: 'CONTINUOUS' },
  { name: 'A-ANNO-TITLE', aciColor: 7, lineType: 'CONTINUOUS' }
];
Enter fullscreen mode Exit fullscreen mode

Define the DASHED linetype inside the LTYPE table before the LAYER table references it (group codes 73 = dash element count, 40 = total pattern length in inches, 49 = positive pen-down / negative pen-up segments).

Coordinate Mapping: Screen Y-Down vs CAD Y-Up

HTML Canvas and SVG place (0, 0) at top-left with +Y pointing downward. AutoCAD model space places (0, 0) at bottom-left with +Y pointing upward. Always normalize coordinates through a single pure transform function:

function toCadInches(xFt: number, yFt: number, roomLengthFt: number): [number, number] {
  return [xFt * 12, (roomLengthFt - yFt) * 12];
}
Enter fullscreen mode Exit fullscreen mode

Emitting Clean Primitives Without R2000 Pitfalls

One subtle trap when targeting R12: LWPOLYLINE did not exist in R12 (it was introduced in R14). If you emit LWPOLYLINE under AC1009, strict importers reject it. Stick strictly to universal R12 entities:

  • LINE (10/20 start, 11/21 end) for walls, aisles, tables, and egress paths.
  • CIRCLE (10/20 center, 40 radius in inches) for 60" / 72" round banquet tables and 75-foot (900-inch) NFPA 10 fire extinguisher coverage radii.
  • ARC (10/20, 40, 50 start angle deg, 51 end angle deg) for door swings.
  • TEXT (10/20 position, 40 text height in inches, 1 text string, 72/73 horizontal/vertical alignment) for room dimensions and exit capacity callouts.

Setting Drawing Extents ($EXTMIN / $EXTMAX)

Always write $INSUNITS = 1 (inches), $LUNITS = 4 (architectural feet-and-inches display), and accurate $EXTMIN / $EXTMAX bounding coordinates in the HEADER section. Without bounding extents, CAD viewers open your drawing zoomed out to 10,000 units with the floor plan appearing as a tiny speck.

Deterministic Verification in Unit Tests

Because the serializer is a pure TypeScript function (PlanModel -> string), you can test every geometric invariant in Vitest in milliseconds:

  1. Validate alternating line parity (lines.length % 2 === 0) and strict ASCII encoding.
  2. Verify every required section (HEADER, TABLES, ENTITIES, EOF) opens and closes cleanly.
  3. Assert that a 40' x 60' room emits perimeter wall endpoints spanning exactly 0.0000 to 480.0000 in X and 0.0000 to 720.0000 in Y.
  4. Confirm zero raw newlines survive inside TEXT group code 1 values even with adversarial titles.

This pure-TypeScript architecture is the exact CAD export pipeline powering EgressCAD (and its free IFC 1007.1.1 Half-Diagonal Exit Separation Calculator), keeping edge latency near zero while giving licensed architects and PEs clean 7-layer .DXF files they can open, inspect, and seal directly.

Top comments (0)