Skip to content

Instantly share code, notes, and snippets.

@snapo
Last active September 11, 2022 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snapo/bc25afef0c6ead982a066b868b4c7f14 to your computer and use it in GitHub Desktop.
Save snapo/bc25afef0c6ead982a066b868b4c7f14 to your computer and use it in GitHub Desktop.
FreeCAD headless export files and use in visual studio code directly with python of your choice (Python <=3.8 required)
# The imports of the FreeCAD library
import os
from os.path import exists as file_exists
import sys
FREECADPATH = 'C:/Program Files/FreeCAD 0.19/bin/'
sys.path.append(FREECADPATH)
FREECADPATH = 'C:/Program Files/FreeCAD 0.19/lib/'
sys.path.append(FREECADPATH)
import PySide2
import six
import FreeCAD as App
import Part
import Mesh
import Sketcher
import Draft
################################
# API Documentation: https://freecad.github.io/SourceDoc/modules.html
################################
projectname = "ProjectX"
# Check if file exists, delete if exists and re-create the file
filename = f'{projectname}.FCStd'
if file_exists(filename) == True:
os.remove(filename)
doc = App.newDocument(projectname)
doc.FileName = filename
# Do our CAD magic.....
# Creating a Mesh
mymesh = Mesh.createSphere()
mymesh.Facets
mymesh.Points
meshobj = doc.addObject("Mesh::Feature", "MyMesh")
meshobj.Mesh = mymesh
App.getDocument('ProjectX').getObject('MyMesh').Placement = App.Placement(App.Vector(0,5.0,-20.0),App.Rotation(App.Vector(0,0,1),0))
# Create a Feature
myfeature = Part.makeSphere(5)
myfeature.Volume
myfeature.Area
shapeobjfeature = doc.addObject("Part::Feature", "MyShape")
shapeobjfeature.Shape = myfeature
# Use Sketches
s1 = App.ActiveDocument.addObject("Sketcher::SketchObject",'MyFirstSketch')
s1.addGeometry(Part.Circle(App.Vector(0.000,0.000,0),App.Vector(0,0,1),10.123456),False)
App.getDocument('ProjectX').getObject('MyFirstSketch').addConstraint(Sketcher.Constraint('Radius',0,10.123456))
App.getDocument('ProjectX').getObject('MyFirstSketch').setDatum(0,App.Units.Quantity('20.000000 mm'))
App.getDocument('ProjectX').getObject('MyFirstSketch').movePoint(0,3,App.Vector(8.5,7.6,0),0)
# Re-Compute everything and Export Step file and STL files and save the document...
App.ActiveDocument.recompute()
o = FreeCAD.getDocument(projectname).findObjects()[0]
Mesh.export([o], f"{projectname}.stl")
Part.export([o], f"{projectname}.step")
doc.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment