Considering the issues we face while working with the pyautocad module or while working with some of the functions provisioned, we decided to write a blog post to discuss one other method to integrate python with AutoCAD, i.e. by using the pywin32 library.
1. Introduction to pywin32 (win32com module)
The pywin32 package provides access to many of the Windows APIs from Python.
We can interact with different windows applications such as Excel, word, AutoCAD itself, etc. by using VBA object models for the respective application.
This pywin32 package supports only Python 3 and not the older version of Python.
To install the pywin32 package we can simply use our Python package manager, pip and
pip install pywin32
Now, to use this package we have to import the module “win32com.client”.
2. VBA object model for AutoCAD
Most of the applications we use in windows has its own object model. For AutoCAD VBA (Visual Basic for Applications) has its own object model too.
VBA enables the creation of user-defined functions (UDFs). It furthermore allows for process automatization and provides access to the Windows API as well as other low-level functionality. This is facilitated through dynamic-link libraries (DLLs). Let’s take a look at the VBA object model as provided and described in the AutoCAD documentation.
3. Initiating a drawing template using pywin32
Those who have already used VBA for automation purposes in AutoCAD can relate the commands with the object model as shown in Figure 1. For example, Application is the root model at which the actual document is located.
We work on a single AutoCAD template or sheet, which is known as “model space”.
Now, to open a new drawing sheet using VBA, we use the following line of code in VBA:
NewDrawing1 = ThisDrawing.Application.Documents.Add("")
To perform the same action with the pywin32 package we can use :
import win32com.client acad = win32com.client.Dispatch("AutoCAD.Application") acad.Visible = True acadModel = acad.ActiveDocument.ModelSpace
Clearly, we can relate the above-mentioned codes as given below
To initiate AutoCAD application > ThisDrawing.Application. = win32com.client.Dispatch(“AutoCAD.Application”)
acad.Visible = True
To create a new template > .Documents.Add(“”) = acad.ActiveDocument.ModelSpace
Also, we can see from our previous blog posts related to pyautocad that we used to initiate the application as well as model space using the method-call Autocad(create_if_not_exists=True).
In the upcoming blogs will be discussing more regarding how to perform different tasks using pywin32.
Civil engineer interested in automation in core subjects such as civil, mechanical and electrical, using IT skills comprising cloud computing, devops, programming languages and databases along with the technical skills gained while working as a civil engineer since past 3 years.