Usage

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)

Working with tables

Note

To work with tables, xlrd and tablib should be installed.

To simplify importing and exporting data there is Table class exist. It allows you to read and write tabular data in popular formats:

  • csv
  • xls
  • xlsx (write only)
  • json

Let’s try to solve some basic task. We need to save text and position from all text objects to Excel file, and then load it back.

First we need to add some objects to AutoCAD:

from pyautocad import Autocad, APoint
from pyautocad.contrib.tables import Table

acad = Autocad()
p1 = APoint(0, 0)
for i in range(5):
    obj = acad.model.AddText(u'Hi %s!' % i, p1, 2.5)
    p1.y += 10

Now we can iterate this objects and save them to Excel table:

table = Table()
for obj in acad.iter_objects('Text'):
    x, y, z = obj.InsertionPoint
    table.writerow([obj.TextString, x, y, z])
table.save('data.xls', 'xls')

After saving this data to ‘data.xls’ and probably changing it with some table processor software (e.g. Microsoft Office Excel) we can retrieve our data from file:

data = Table.data_from_file('data.xls')

data will contain:

[[u'Hi 0!', 0.0, 0.0, 0.0],
 [u'Hi 1!', 0.0, 10.0, 0.0],
 [u'Hi 2!', 0.0, 20.0, 0.0],
 [u'Hi 3!', 0.0, 30.0, 0.0],
 [u'Hi 4!', 0.0, 40.0, 0.0]]

See also

Example of working with AutoCAD table objects at examples/dev_get_table_info.py

Improve speed

  • ActiveX technology is quite slow. When you are accessing object attributes like position, text, etc, every time call is passed to AutoCAD. It can slowdown execution time. For example if you have program, which combines single line text based on its relative positions, you probably need to get each text position several times. To speed this up, you can cache objects attributes using the pyautocad.cache.Cached proxy (see example in class documentation)

  • To improve speed of AutoCAD table manipulations, you can use Table.RegenerateTableSuppressed = True or handy context manager suppressed_regeneration_of(table):

    table = acad.model.AddTable(pos, rows, columns, row_height, col_width)
    with suppressed_regeneration_of(table):
        table.SetAlignment(ACAD.acDataRow, ACAD.acMiddleCenter)
        for row in range(rows):
            for col in range(columns):
                table.SetText(row, col, '%s %s' % (row, col))
    

Utility functions

There is also some utility functions for work with AutoCAD text objects and more. See pyautocad.utils documentation.