While working with AutoCAD, correct description is very important. In such cases, we have to add texts to our AutoCAD drawings. In this blog post we are going to discuss how to work with normal texts & multiline texts using Python.
1. Setting up the environment for pyautocad
First of all, we will set up our work environment to integrate Python with AutoCAD by importing our pyautocad library.
from pyautocad import Autocad, APoint acad = Autocad()
2. Working with normal texts with pyautocad
To insert a text string in an AutoCAD template, we need a very simple command. Let’s check out the syntax and use it.
acad.model.AddText(Text String, Insertion Point, Text Height)
t1 = acad.model.AddText("Hello", APoint(75, 50), 25)
We can observe from the property box in Figure 1, that the text has been inserted as per the parameters passed by us.
Moving forward, we can also fetch some properties related to the text, for instance, text alignment, height, rotation, scale factor, etc.
Let’s take a look at them.
print("Text content: " + t1.TextString) print("Text style: " + t1.StyleName) print("Text insertion point: ", end=" " ) print(t1.InsertionPoint) print("Text alignment: " + str(t1.Alignment)) print("Text alignment point: " + str(t1.TextAlignmentPoint)) print("Text height: " + str(t1.Height)) print("Text rotation: " + str(t1.Rotation)) print("Text scale factor: " + str(t1.ScaleFactor)) print("Is the text upside down: " + str(t1.UpsideDown)) O/p: Text content: Hello Text style: Standard Text insertion point: (75.0, 50.0, 0.0) Text alignment: 0 Text alignment point: (0.0, 0.0, 0.0) Text height: 25.0 Text rotation: 0.0 Text scale factor: 1.0 Is the text upside down: False
We can change the text and its properties using these functions. Let’s try the same.
t1.TextString = "Hi" t1.Height = 50 t1.Rotation = 2 t1.ScaleFactor = 1 t1.UpsideDown = True
3. Working with multi-line texts with pyautocad
Sometimes, we need to be more descriptive in the drawing to explain certain attributes, in that case, we need long sentences and hence the need for multiline texts arises. With this, we can set horizontal limits for the text we want to enter.
The command for multiline text is as simple as that of normal text.
acad.model.AddMText(Insertion Point, Width, Text String)
mt1 = acad.model.AddMText(APoint(275, 150), 100, "This is auotocad text") mt1.Height = 25
Here, after using the text command, we have set the text height specifically, otherwise, the text would have got created using the default text size in that AutoCAD template.
For more information on AutoCAD itself, you can also review the Autodesk documentation.
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.