← LibraryFirst SolidWorks Automation Tasks: Batch Export and Document InformationEngineering · ComputersLesson 4/10← PrevNext →
ArticlePublished 4 Aug 20268 min readBy Kevin JoginSolidWorks APIDXF exportbatch processingCAD automation

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.

4Guards before any document is touched
2Outputs to read after every save
mThe API's length unit, whatever the document is set to

01The guard preamble

Every tool in this series opens the same way. It is worth writing once, understanding thoroughly, and reusing without variation.

Guard 1Application objectPresent by definition in a macro; obtained by attach or launch in a .NET client.
Guard 2Document existsThe active document may legitimately be nothing. Test before use.
Guard 3Correct typeCompare against the document type enumeration, not an integer literal.
Guard 4Saved and writableAn unsaved document has no path to derive output names from; a read-only one cannot be modified.
C#the preamble, complete
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.

Also worth testing

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.

C#sheet loop with state restored
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 were

The 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.

Activation is not free

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.

C#export the active sheet, then check both outputs
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.
Export options live outside the code

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.

Where document information lives
SourceHoldsNotes
Document membersTitle, full path, read-only and view-only state, active configuration, rebuild stateDirect properties and simple calls on the document object
Summary informationTitle, subject, author, keywords, comments, who saved it, creation and modification datesIndexed by members of the summary information enumeration
Custom propertiesAnything your organisation defines — part number, material, finish, revision, projectThe subject of Part 7; the richest source and the most valuable
C#assembling a document report
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));
Audit before you automate

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.

System units, always

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.

  1. 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.
  2. 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.
  3. Summarise at the endCounts of written, skipped and failed. Users read the summary; the detail is there for when it disagrees with expectations.
  4. 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.
  5. Handle the interruptionDecide what a cancelled run leaves behind, and make sure a half-finished batch is recognisable as one.
  6. Make it idempotentRunning twice should be harmless. If your rule appends a counter, the second run has silently doubled the deliverables.
Verification, not just testing

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.

07Quick reference

IDrawingDoc::GetSheetNames
Names of every sheet, as an array to cast in C#.
IDrawingDoc::ActivateSheet
Makes a sheet current. Restore the original before exiting.
IModelDocExtension::SaveAs3
Writes the document; format follows the file extension. Outputs errors and warnings by reference.
swSaveAsOptions_e
Bit flags for save behaviour, including silent operation and copy mode.
IModelDoc2::GetPathName
Full path; empty for a document never saved.
IModelDoc2::IsOpenedReadOnly
True where the document can be read but not written back.
IModelDoc2::SummaryInfo
Indexed by swSummInfoField_e — author, saved by, comments, dates.
IModelDoc2::GetConfigurationNames
Every configuration name in the document.
System units
Metres, radians, kilograms — irrespective of document display units.

Continue learning

Connecting to SolidWorks from Visual Studio in C# and VB.NETArticle · ComputersNEXT LESSON →Working with Selected Objects in the SolidWorks APIArticle · ComputersSolidWorks API Macro Fundamentals: Recording, Reading and WritingArticle · ComputersSolidWorks PropertyManager Pages: Building Native User InterfaceArticle · Computers