Main interface and types¶
For our first example, we will use Autocad (main Automation object) and pyautocad.types.APoint for operations with coordinates
from pyautocad import Autocad, APoint
Let’s create AutoCAD application or connect to already running application:
acad = Autocad(create_if_not_exists=True)
acad.prompt("Hello, Autocad from Python\n")
print acad.doc.Name
To work with AutoCAD documents and objects we can use ActiveX interface, Autocad (from pyautocad) contains some methods to simplify common Automation tasks, such as object iteration and searching, getting objects from user’s selection, printing messages.
There are shortcuts for current ActiveDocument - Autocad.doc and ActiveDocument.ModelSpace - Autocad.model
Let’s add some objects to document:
p1 = APoint(0, 0)
p2 = APoint(50, 25)
for i in range(5):
text = acad.model.AddText(u'Hi %s!' % i, p1, 2.5)
acad.model.AddLine(p1, p2)
acad.model.AddCircle(p1, 10)
p1.y += 10
Now our document contains some Texts, Lines and Circles, let’s iterate them all:
for obj in acad.iter_objects():
print obj.ObjectName
Wea can also iterate objects of concrete type:
for text in acad.iter_objects('Text'):
print text.TextString, text.InsertionPoint
Note
Object name can be partial and case insensitive, e.g. acad.iter_objects('tex') will return AcDbText and AcDbMText objects
Or multiple types:
for obj in acad.iter_objects(['Text', 'Line']):
print obj.ObjectName
Also we can find first object with some conditions. For example, let’s find first text item which contains 3:
def text_contains_3(text_obj):
return '3' in text_obj.TextString
text = acad.find_one('Text', predicate=text_contains_3)
print text.TextString
To modify objects in document, we need to find interesting objects and change its properties. Some properties are described with constants, e.g. text alignment. These constants can be accessed through ACAD. Let’s change all text objects text alignment:
from pyautocad import ACAD
for text in acad.iter_objects('Text'):
old_insertion_point = APoint(text.InsertionPoint)
text.Alignment = ACAD.acAlignmentRight
text.TextAlignmentPoint = old_insertion_point
In previous code we have converted text.InsertionPoint to APoint because we can’t just use default tuple when setting another properties such as text.TextAlignmentPoint.
If wee need to change position of some object, we should use APoint, for example let’s change lines end position:
for line in acad.iter_objects('Line'):
p1 = APoint(line.StartPoint)
line.EndPoint = p1 - APoint(20, 0)