Write DGN V8 from a seed
cadkit writes DGN V8 into a seed: an existing single-model V8 file whose tables (levels, fonts, colour table, text styles, views, settings, units) the output inherits. cadkit ships no seed of its own, because the file header and model header that every seed needs hold fields whose meaning is not decoded and whose values differ between the writers of the public samples. You make a seed from a drawing whose tables you may hand on, such as your organisation’s template.
The three steps
Section titled “The three steps”- Strip a seed.
strip-seedcopies the template without its model’s drawing content and without the document properties that name people or organisations (author, company, manager, title, comments, thumbnail), and rebuilds the container so no removed byte survives. Names in the kept tables remain: level names, tag sets, cell and font names and the model description. The report counts them; review them before you hand the seed on. The result is not anonymous. - Prepare the document. The writer needs one model whose dimension (2D or 3D) and units
match the seed, colours that exist in the seed’s palette, and measured advances for centred
or right-aligned text. In Rust and Python,
V8Seed::prepare_document/seed.prepare_documentdoes this by default: it selects the first design model, converts units, promotes a 2D drawing to a 3D seed, expands block references and normalises symbology (off-palette colours to the nearest palette index,ByBlock, millimetre lineweights, unknown fonts), polyline widths, multiline text, leaders, hatches and text alignment.SeedPrepareOptionsturns each part off. The JavaScript and C APIs have no preparation step; their callers supply a matching document. - Write and check.
to_dgnwrites the model into a copy of the seed.check_structure(Rust, andcadkit check-dgn) reports the container and record structure with stable warning codes.
use cadkit::ReadOptions;use cadkit::dgn::{SeedPrepareOptions, StripSeedOptions, V8Seed, WriteOptions};
fn main() -> Result<(), Box<dyn std::error::Error>> { // 1. A seed: a DGN V8 file whose tables you may hand on, without its drawing content. let template = std::fs::read("template.dgn")?; let options = StripSeedOptions::new().with_model_name(Some("Model")); let stripped = cadkit::strip_dgn_seed(&template, &options, &ReadOptions::default())?; let report = &stripped.report; println!("kept: {} named levels, {} tag sets", report.named_levels, report.tag_sets); let seed = V8Seed::from_bytes(&stripped.bytes)?;
// 2. Adapt the drawing to the seed (model, units, 2D to 3D, colours), then write. let doc = seed.prepare_document(&cadkit::open("plan.dxf")?, &SeedPrepareOptions::new())?; let bytes = cadkit::to_dgn_with_seed(&doc, &seed, &WriteOptions::new())?; std::fs::write("converted.dgn", &bytes)?;
// 3. Check the container and records with cadkit's own structural report. let structure = cadkit::dgn::check_structure(&bytes, &ReadOptions::default())?; println!("structure warnings: {}", structure.warnings.len()); Ok(())}import cadkit
# 1. A seed: a DGN V8 file whose tables you may hand on, without its drawing content.with open("template.dgn", "rb") as f: seed_bytes, report = cadkit.strip_dgn_seed(f.read(), model_name="Model")print("kept:", report["named_levels"], "named levels,", report["tag_sets"], "tag sets")seed = cadkit.V8Seed(seed_bytes)
# 2. Adapt the drawing to the seed (model, units, 2D to 3D, colours), then write.doc = seed.prepare_document(cadkit.read("plan.dxf"))with open("converted.dgn", "wb") as f: f.write(doc.to_dgn(seed))
# 3. Read the result back with cadkit's own reader.print(cadkit.read("converted.dgn"))import { readFileSync, writeFileSync } from "node:fs";import { CadDocument, inspect, read, stripDgnSeed } from "cadkit-wasm/node";
// 1. A seed: a DGN V8 file whose tables you may hand on, without its drawing content.const { seed, report } = stripDgnSeed(readFileSync("template.dgn"), { modelName: "Model" });console.log("kept:", report.named_levels, "named levels,", report.tag_sets, "tag sets");
// 2. cadkit-wasm has no seed preparation (Rust and Python do): match the seed by hand.const target = inspect(seed); // the seed's units and 2D/3Dconst source = read(readFileSync("plan.dxf"));source.convertUnits(target.units.unit); // mutates the documentconst json = source.toJSON();source.free();const model = { ...json.models[0], is_3d: target.is_3d }; // one model, the seed's dimensionfor (const { kind, props } of model.entities) { props["dgn.color_index"] ??= 0; // a seed palette index: map your colours here if (kind.type === "text" && kind.halign !== "left") { // Centred and right-aligned text needs its advance in drawing units: measure it with // your fonts. This is the estimate prepare_document applies. props["dgn.text_length"] ??= [...kind.value].length * kind.height * kind.width_factor * 0.6; }}json.models = [model];
// 3. Write, then read the result back with cadkit's own reader.const doc = CadDocument.fromJsonString(JSON.stringify(json));writeFileSync("converted.dgn", doc.toDgn(seed));doc.free();const check = read(readFileSync("converted.dgn"));console.log(check.info().format, check.info().models[0].entities, "entities");check.free();#include <stdio.h>#include <stdlib.h>#include "cadkit.h"
/* Reads a whole file into memory; returns NULL on failure. */static uint8_t *load(const char *path, size_t *len) { FILE *f = fopen(path, "rb"); if (!f) return NULL; uint8_t *data = NULL; if (fseek(f, 0, SEEK_END) == 0) { long size = ftell(f); if (size > 0 && fseek(f, 0, SEEK_SET) == 0 && (data = malloc((size_t)size)) != NULL) { *len = fread(data, 1, (size_t)size, f); } } fclose(f); return data;}
int main(void) { size_t template_len = 0; uint8_t *template_bytes = load("template.dgn", &template_len); if (!template_bytes) return 1;
/* 1. A seed without the template's drawing content; the report counts what remains. */ uint8_t *seed = NULL; size_t seed_len = 0; char *report = NULL; cadkit_status st = cadkit_dgn_strip_seed(template_bytes, template_len, "{\"model_name\":\"Model\"}", NULL, &seed, &seed_len, &report); free(template_bytes); if (st != CADKIT_OK) { fprintf(stderr, "%s\n", cadkit_last_error_message()); return 1; } printf("%s\n", report); cadkit_string_free(report);
/* 2. The C API has no seed preparation, so the document must already match the seed: one model, the seed's units and dimension, colours as seed palette indices, measured text. A DGN V8 drawing written for the same seed family does. */ cadkit_document *doc = NULL; uint8_t *dgn = NULL; size_t dgn_len = 0; int rc = 1; if (cadkit_read_file("drawing.dgn", NULL, &doc) == CADKIT_OK && cadkit_document_to_dgn(doc, seed, seed_len, NULL, &dgn, &dgn_len) == CADKIT_OK) { FILE *out = fopen("converted.dgn", "wb"); if (out) { rc = fwrite(dgn, 1, dgn_len, out) == dgn_len ? 0 : 1; fclose(out); } } else { fprintf(stderr, "%s\n", cadkit_last_error_message()); } cadkit_bytes_free(dgn); /* binary buffers: cadkit_bytes_free, never cadkit_string_free */ cadkit_bytes_free(seed); cadkit_document_free(doc); return rc;}The JavaScript version shows by hand what preparation involves. Two of its steps are
placeholders you replace: every entity gets palette index 0, and text advances use the same
character-count estimate as prepare_document. Measure text with the fonts you use for exact
placement.
From the shell
Section titled “From the shell”cadkit strip-seed template.dgn seed.dgn --model-name Model --report > seed-report.jsoncadkit layers seed.dgn # review the level names the seed keepscadkit convert drawing.dgn converted.dgn --seed seed.dgncadkit check-dgn converted.dgn > structure.json # exits 1 when the report has warningsThe CLI strips, checks and repacks seeds, and convert --seed writes a document as read,
without preparation. A DXF or DWG file with paper layouts fails with DGN writer requires exactly one source model, and a 2D drawing into a 3D seed with source and seed model dimensions differ. For those conversions use Python or Rust.
What the writer supports
Section titled “What the writer supports”New elements: lines, line strings, closed shapes, circles, ellipses, arcs, left, centre and
right text at baseline, middle or top, complex chains and shapes, and ordinary cell groups.
Bulged polylines become exact line and arc components; faces and meshes become shapes and
cells; polygons with holes become a cell with hole-marked shapes. Levels, tag sets and tag
values are writable, and strings default to UTF-16 (codepage selects a legacy 8-bit page).
Not supported by the writer yet, and rejected with an Unsupported error instead of being
dropped: shared-cell instances, edited raster attachments, splines, hatches, dimensions, fitted
or oblique text and polylines with a non-zero width. prepare_document normalises hatch geometry and
polyline widths (with multiline text and leaders) for the writer; convert the others
explicitly before writing.
Colours must exist in the seed palette unless you give dgn.color_index yourself, and
ByBlock colours need resolving first.
Writing into a seed that already holds drawing content requires clear_seed_model (CLI:
--clear-seed-model). Rewriting an existing DGN with its own bytes as the seed keeps its
unchanged raster attachments. The details, with the evidence for each layout, are in the
DGN format notes.