Working with AutoCAD texts in pyautocad

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.

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()

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.

Syntax:

acad.model.AddText(Text String, Insertion Point, Text Height)

t1 = acad.model.AddText("Hello", APoint(75, 50), 25)
Figure 1.1: Text using pyautocad

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
Figure 1.2: Changed properties of text using pyautocad

Working with multi-line AutoCAD text objects in 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.

Syntax:

acad.model.AddMText(Insertion Point, Width, Text String)

mt1 = acad.model.AddMText(APoint(275, 150), 100, "This is auotocad text")
mt1.Height = 25
Figure 2: Multi-line text with pyautocad

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.

You May Also Like

Leave a Reply

29 comments

Shaunak Deshpande says:

Can you please tell me how to align(centre) text using pyautocad? I tried to do it but didn’t know its syntax.

Hello Mr. Deshpande,

Thanks for your question, we have a method called, Alignment, but that works only with the Text object and not multiline texts. This can be set to the desired value by using “text.Alignment = 0/1/2 and so on”.

But the results we get are a bit odd as compared to what we expect. Hopefully, soon we will bring some solution for the same.

Have a nice day!

Shaunak Deshpande says:

Hi, thank you for the reply. Could you please give an example by implementing the above method of text.Alignment = 0/1/2.
Thank you.

Robbin says:

Yes please, text.Alignment = 1 lets the text disappear.

Shaunak Deshpande says:

Where can I find the syntax and use of all the functions in pyautocad?
Are there any books or documentation(other than readthedocs.io) for pyautocad? Please let me know.
Thanks.

Hello Mr. Deshpande,

There is no particular page for using python syntax for automating AutoCAD. Hence we are documenting how to use pyautocad on this blog.
But you can find the pyautocad module’s official page and ActiveX documentation by Autodesk for more information to understand how to use the same.

Have a great day!

EngineerTech says:

How do you draw in paperspace or one of the layout
I see all the method in acad.model.

Hi,

Thanks for the question.
When we use acad it is actually generating a template with sheets named model, layout1 and layout2 after we assign acad to .AutoCAD(create_if_not_exists=True).

Whatever we draw on that model space gets replicated to paperspace.

Tekoha says:

Hello!

Is there a way to make linear dimensions?

Hi,

Thanks for your question.
Yes you can use AddDimAligned method as given below:

object.AddDimAligned(ExtLine1Point, ExtLine2Point, TextPosition)

where,
ExtLine1Point : First end point (3 elemental array of doubles)
ExtLine2Point : Second end point (3 elemental array of doubles)
TestPosition : (3 elemental array of doubles)

You can pass the values by fetching the same from the object on which you want to add dimension.

Have a nice day!

Tekoha says:

Fantastic! Thank Alot!

How do I change the scale of it?

I’m trying to configure it in ways like My_Dim.DimScale = 5 but no luck!

Hi Tekoha,

Soon I am coming up with a blog on dimensions. Stay tuned.

Thank you.

Thank you for the question Tekoha.

As Tanmay stated he will soon publish a blog post on this.

If you have a specific problem we offer consulting at a fair fee. For this you can just contact us via the contact form or on LinkedIn.

Michael says:

I am trying to take make the text that I generate go to a specific Layer. Do you know what command does that?
I have currently:
SO_Text = acad.model.AddText = (“SO NUMBER”, APoint(0, 0), 100)
I have a layer called INPUT_TEXT, so i tried
SO_Text.Layer = INPUT_TEXT
but this didnt work

Hi Michael,

Thanks for the question.

Have you tried using layer as string?
e. g.
SO_Text.Layer = “INPUT_TEXT”

Because when we use Layer method against any object it returns a string.

Have a nice day!

Matt says:

This works but the layer must exist for it to work. If you need to create a new layer use
acad.doc.Layers.Add(“LayerName”)

thanks for comment. for creating layer and assigning objects to layer see below example:

import pyautocad
acad = pyautocad.Autocad()
layers = acad.ActiveDocument.Layers
my_layer = layers.AddLayer(“MyLayer”)
my_line.Layer = my_layer.Name
start_point = pyautocad.APoint(0, 0, 0)
end_point = pyautocad.APoint(1, 1, 0)
my_line = acad.model.AddLine(start_point, end_point, layer=”MyLayer”)

eddy says:

Hello Linnart Felkl M.Sc. I have created 10 different sizes of rectangles that I want to automatically number.
Of the 10 created rectangles, 3ea are the same size and the remaining 7ea are the same size. Can 2 different numbers be generated automatically in pyautocad?

Eddy, thank you for your question. Yes, this is for sure possible and easy to implement. I suggest you send us your drawing and specify exactly what you want the program to do. Also specify if you are OK with executing the program via the terminal (e.g. powershell). You have the rectangles available in some directory or are you drawing them and adding to the drawing, and then your want them to replicated and numbered? Or are they all already available in the drawing?

You can send us this data and info via the contact form on our website. We can implement this for you or a very small fee. Contact form is here: https://www.supplychaindataanalytics.com/contact/

عمر صلاح الخولي says:

hi when I try to add multi-line text and it contains “{”
this letter deleted
example:
copyw =”””H{lhgD ‘,G HgqgU 50.00 ljv
Hglshp_m HB{lhgdm = 2500.00 L2
“””

it appears:
HlhgD ‘,G HgqgU 50.00 ljv
Hglshp_m HBlhgdm = 2500.00 L2

and this is the code
t2=acad.model.AddMText(APoint(0, 0), 100, copyw)

In AutoCAD, curly braces ({ and }) are used to indicate fields in text. If you want to insert curly braces into your text string without them being interpreted as fields, you can escape them by using a pair of opening and closing braces. For example, to insert the text string {example}, you can use the string {{example}}.

Omer elkhooly says:

when I try to add a multi-line text, and it contains “{” this letter disappears

Na verdade o texto não desaparece. Ele é movido para as coordenadas (0, 0).

Usei essa solução para resolver:
from pyautocad import Autocad, APoint

# ‘texto’ > Dado que será inserido no autocad;
# ‘coord’ > Coordenadas inseridas usando a função APoint(x, y);
# ‘alinhamento’ > Alinhamento sendo: Esquerda (0), Centralizado (1), Direita (2);
# ‘altura_texto’ > Altura do texto que será criado.

def txt(texto, coord, alinhamento, altura_texto):
acad = Autocad(create_if_not_exists=True)
t = acad.model.AddText(texto, coord, altura_texto)
t.Alignment = alinhamento
t.Move(APoint(0, 0), coord)

Parece que a solução que você encontrou funciona para resolver o problema de mover o texto para as coordenadas (0,0) ao invés de mantê-lo onde foi criado. No entanto, a linha t.Move(APoint(0, 0), coord) é um pouco confusa, porque ela move o texto para a posição dada em coord, mas a posição final não é a mesma que a posição inicial. Isso pode ser um problema se você precisar fazer cálculos baseados na posição do texto. Uma alternativa seria criar o texto usando a função AddMText, que permite definir uma largura de texto e quebrar o texto em várias linhas:

def txt(texto, coord, alinhamento, altura_texto):
acad = Autocad(create_if_not_exists=True)
t = acad.model.AddMText(coord, 10, texto)
t.Width = 100
t.AttachmentPoint = alinhamento
t.Height = altura_texto

Walter says:

Can i take text from excel column, and write im coordinates indicated in other excel’s columns? The excel file has a column format like: point number, x, y, z.. thanks in advance. Sorry for my english.

Hi Walter, sure you can. In the search function of this blog search for Excel. You will find an article that shows how to use Excel and pyautocad for AutoCAD

Joshua says:

Hello, I have created a Block with one Attribute. I have been trying to center the text of that Attribute within the block. I apologize if this has a simple answer, but I have looked through the pyautocad docs as well as the AutoDesk docs. I’ve tried using .Alignment, .TextAlignmentPoint, etc and nothing seems to be working.
I’m completely new to this. Can anyone help? Thank you for your time.

ip = APoint(0,0,0)
b1 = acad.doc.Blocks.Add(ip, blockName)
p1 = b1.AddPolyline(aDouble(0,0,0, 5.3382,0,0, 5.3382,.1250,0, 0,.1250,0, 0,0,0))
a1 = b1.AddAttribute(.0625, 0, “BOM”, aDouble(.05, .03125, 0), “BOM”, sh.cell(row, col).value)
block_ref1 = acad.model.InsertBlock(APoint(10, 10 + yStack, 0), blockName, 1, 1, 1, 0)

DOO LEE says:

hello, I only want to change the color of the specific text in the drawing. I have so many drawings. Can i do this?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.