Engineering / Computers / Part 3 of 9
First Automation Tasks
Batch-exporting every sheet of a drawing is the task that convinces most engineering offices the API is worth learning. It is also an ideal first project: the rules are unambiguous, the benefit is immediate and visible, and building it properly teaches the guard-and-error discipline that everything else depends on.
- Part 3 · Applied
- Sheet loop → DXF
- Error & warning codes
- Metres and radians
KL-ENG-COMP-1503 · KEVOS® Knowledge Library · Australian English
Three capabilities cover a surprising proportion of practical automation: getting a verified handle to the right document, walking a collection inside it, and writing files out under a naming rule. This part builds all three around a single worked task and then turns to reading the information a document already carries.
01The guard preamble
Every tool in this series opens the same way. It is worth writing once, understanding thoroughly, and reusing without variation.
IModelDoc2 swModel = swApp.ActiveDoc as IModelDoc2;
if (swModel == null)
{
MessageBox.Show("Open a drawing first.");
return;
}
if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING)
{
MessageBox.Show("The active document is not a drawing.");
return;
}
string sourcePath = swModel.GetPathName();
if (string.IsNullOrEmpty(sourcePath))
{
MessageBox.Show("Save the drawing before exporting, so outputs can be named from it.");
return;
}The fourth guard is the one most often omitted and the one that produces the strangest failures. A document that has never been saved returns an empty path, and any naming rule built from that path silently produces files in unexpected places.
IsOpenedReadOnly and IsOpenedViewOnly report documents you can
read but not modify — common where a vault or a network permission is involved.
Checking them before a tool that writes back saves a confusing failure much later in the
run.
02Walking the sheets of a drawing
A drawing document exposes its sheets by name. The pattern is: read the names, activate each in turn, act, and restore the sheet that was active when you started.
IDrawingDoc swDrawing = (IDrawingDoc)swModel;
string[] sheetNames = (string[])swDrawing.GetSheetNames();
string startedOn = ((ISheet)swDrawing.GetCurrentSheet()).GetName();
foreach (string sheetName in sheetNames)
{
swDrawing.ActivateSheet(sheetName);
// ... act on this sheet ...
}
swDrawing.ActivateSheet(startedOn); // put the user back where they wereThe final line is not decoration. A tool that leaves the user on sheet seven of a twelve-sheet drawing has interfered with their work, and that is what they will remember about it.
Activating a sheet causes work in the application. On large drawings a loop over many sheets is noticeably slow, and on very large ones it can appear to hang. Report progress, and where the operation is long, tell the user how many sheets there are before you start.
03Exporting each sheet
With a sheet active, exporting is a single save call to a path whose extension selects the format. The whole batch exporter is the loop above with one call inside it and a naming rule beside it.
int errors = 0, warnings = 0;
string target = System.IO.Path.Combine(
outputFolder,
System.IO.Path.GetFileNameWithoutExtension(sourcePath) + "-" + sheetName + ".dxf");
bool ok = swModel.Extension.SaveAs3(
target,
(int)swSaveAsVersion_e.swSaveAsCurrentVersion,
(int)swSaveAsOptions_e.swSaveAsOptions_Silent,
null, null,
ref errors, ref warnings);
if (!ok || errors != 0)
log.Add($"FAILED {sheetName} (error {errors}, warning {warnings})");
else if (warnings != 0)
log.Add($"written with warning {warnings}: {target}");
else
log.Add($"written: {target}");The naming rule is a design decision
Output names carry meaning downstream. Decide deliberately and document it:
- Derive from the source file name so the origin of any output is obvious from the output alone.
- Include the sheet name, since sheets frequently correspond to separate parts or separate operations.
- Sanitise the result. Sheet names may contain characters the file system will not accept. Replace them on a defined rule rather than letting the save fail unpredictably.
- Decide on collisions before they happen. Overwrite, skip, or write alongside — but choose, and make the choice visible in the log.
What a DXF actually contains — which entities are included, how sheet layout is mapped, how fonts and hatching are handled — comes from the export settings in system options, not from the save call. Configure them once, export a known drawing, open the result in the receiving system, and verify. Then record those settings with the tool: an exporter validated under one configuration and run under another is producing something nobody has checked.
04Reading what a document already knows
Documents carry a large amount of information that is useful in reports, audits and file naming. It is spread across three sources.
| Source | Holds | Notes |
|---|---|---|
| Document members | Title, full path, read-only and view-only state, active configuration, rebuild state | Direct properties and simple calls on the document object |
| Summary information | Title, subject, author, keywords, comments, who saved it, creation and modification dates | Indexed by members of the summary information enumeration |
| Custom properties | Anything your organisation defines — part number, material, finish, revision, project | The subject of Part 7; the richest source and the most valuable |
var report = new System.Text.StringBuilder();
report.AppendLine("Title: " + swModel.GetTitle());
report.AppendLine("Path: " + swModel.GetPathName());
report.AppendLine("Read-only: " + swModel.IsOpenedReadOnly());
report.AppendLine("Author: " +
swModel.SummaryInfo[(int)swSummInfoField_e.swSumInfoAuthor]);
report.AppendLine("Saved by: " +
swModel.SummaryInfo[(int)swSummInfoField_e.swSumInfoSavedBy]);
string[] configs = (string[])swModel.GetConfigurationNames();
report.AppendLine("Configs: " + string.Join(", ", configs));A read-only reporting tool is the ideal first deliverable in a business that has not automated before. It cannot damage anything, it produces evidence immediately, and the evidence is usually the strongest argument for the changes you want to make next.
05The units trap
This is the single most common source of numerically wrong results in SOLIDWORKS automation, and it catches experienced engineers because it is invisible.
The API works in system units regardless of what the document is
displaying. Lengths are in metres, angles in radians, mass
in kilograms. A model shown in millimetres still returns a hole diameter of
0.012, not 12. Writing 12 back to that dimension
produces a twelve-metre hole, and the model will rebuild without complaint.
Convert at the boundary
Convert once, where values enter and leave your program, and work in system units everywhere in between. Converting throughout the code guarantees an inconsistency eventually.
Name the variables
A variable called lengthMetres or angleRadians makes the
error visible on the line where it happens rather than in the output.
Sanity-check the magnitude
Before writing a dimension, test that the value falls inside a plausible range. A cheap assertion here prevents an entire class of silent corruption.
The same principle governs mass properties, distances between entities, and any coordinate you receive or supply. Where a value crosses the API boundary, assume system units until the reference tells you otherwise.
06Turning a script into a production tool
The gap between something that worked once and something a team can rely on is a short list of unglamorous additions.
- Take the output location as an inputAsk the user, or read it from a configuration file. Never embed a path belonging to the machine you developed on.
- Log every itemOne line per sheet, stating what was written or why it was skipped. Write the log beside the outputs so it travels with them.
- Summarise at the endCounts of written, skipped and failed. Users read the summary; the detail is there for when it disagrees with expectations.
- Report progressAny run over a few seconds needs to show that it is alive. Silence reads as a crash, and the user will end the process.
- Handle the interruptionDecide what a cancelled run leaves behind, and make sure a half-finished batch is recognisable as one.
- Make it idempotentRunning twice should be harmless. If your rule appends a counter, the second run has silently doubled the deliverables.
For an exporter, the acceptance test is not that files appeared. It is that a representative output, opened in the system that will consume it, contains the geometry and layers expected. Verify against the downstream process, on real drawings, before anyone relies on it.
