Export Shape to STEP Programmatically in FreeCAD

Exporting shapes to the STEP format programmatically in FreeCAD can be achieved using its built-in Python scripting API. By utilizing either the Part module or the export methods available on underlying CAD shapes, you can automate conversions, batch-process geometry, and run headless export scripts without opening the FreeCAD graphical user interface.

Method 1: Exporting Directly from a Document Object

The most common method is using the Part.export() function to save an object from an active FreeCAD document. This function accepts a list of objects and the target file path.

import FreeCAD
import Part

# Access the active document
doc = FreeCAD.ActiveDocument

# Retrieve your target object by its name
obj = doc.getObject("MyPart")

# Export the object as a STEP file
Part.export([obj], "/path/to/output.step")

You can pass multiple document objects inside the list to combine them into a single STEP assembly.

Method 2: Using the exportStep Method on a TopoShape

If you are generating geometry directly through the Part module without adding it to the FreeCAD document tree, you can invoke the exportStep() method directly on the shape instance (Part.TopoShape).

import Part

# Create a primitive shape (e.g., a box)
box = Part.makeBox(10, 10, 10)

# Export the TopoShape directly
box.exportStep("/path/to/output.step")

If you already have a document object, you can access its shape via obj.Shape.exportStep("/path/to/output.step").

Method 3: Using the Import Module

FreeCAD also provides the Import module, which contains higher-level file I/O operations and automatically handles appropriate format parsers based on the file extension.

import FreeCAD
import Import

doc = FreeCAD.ActiveDocument
obj = doc.ActiveObject

# Export using the Import module
Import.export([obj], "/path/to/output.step")

Headless Standalone Script Example

To run this process in a standalone Python script outside the FreeCAD interface, ensure the FreeCAD library path is accessible to Python, load the file, and trigger the export:

import sys

# Append FreeCAD lib path if not already in system paths
sys.path.append("/usr/lib/freecad/lib")  # Update to your local FreeCAD lib directory

import FreeCAD
import Part

# Open an existing document
doc = FreeCAD.openDocument("/path/to/model.FCStd")

# Find the object and export
target_obj = doc.getObject("Body")
Part.export([target_obj], "/path/to/exported_model.step")

# Close document cleanly
FreeCAD.closeDocument(doc.Name)