Adding text to a DWG drawing is often part of a larger engineering work. In certain cases, you might need to label equipment, identify rooms, add revision references, or place notes at predefined coordinates. When those details come from a database or a spreadsheet, adding each label manually in a CAD editor is unnecessary work.
Aspose.CAD for Python via .NET lets you load a DWG drawing, add a text entity to its model space, and export the annotated content. In this tutorial, you will add text to a DWG drawing using Python, set its position and appearance, and save the result as DXF and PDF.
Install Aspose.CAD for Python via .NET
You need a working Python environment, Aspose.CAD package, and a DWG file to annotate. AutoCAD is not required to run this example.
Install the package with pip:
pip install aspose-cad
For additional setup details, see the Aspose.CAD installation guide.
Place a DWG file named sample.dwg in the same folder as your Python script. The example uses model-space coordinates (100, 100, 0) and a text height of 5.0 drawing units. You may need to adjust these values to fit your drawing.
Add Text to a DWG Drawing in Python
CAD drawings store text as entities rather than pixels. The CadText class represents a single-line TEXT entity, with properties for its content, location, height, style, and layer. Adding such an entity keeps the annotation part of the CAD model instead of merely drawing words over an exported picture.
The workflow is to load the DWG file, locate its model-space block, create a CadText entity, add it to that block, update the drawing bounds, and export the result.
Complete Python Code to Insert Text in a DWG Drawing
The following example has been tested with Aspose.CAD for Python via .NET. It adds the label Hello from Aspose.CAD Python to the drawing and produces two output files.
import aspose.cad as cad
from aspose.pycore import cast
from aspose.cad.fileformats.cad import CadImage
from aspose.cad.fileformats.cad.cadobjects import (
CadText,
Cad3DPoint,
)
from aspose.cad.imageoptions import (
DxfOptions,
PdfOptions,
CadRasterizationOptions,
)
# Input and output files
input_file = "sample.dwg"
output_dxf = "drawing_with_text.dxf"
output_pdf = "drawing_with_text.pdf"
# Text properties
text_value = "Hello from Aspose.CAD Python"
text_x = 100.0
text_y = 100.0
text_height = 5.0
# Load the DWG drawing
with cad.Image.load(str(input_file)) as image:
# IMPORTANT: Cast Image to CadImage
cad_image = cast(CadImage, image)
# Find model space
model_space = None
for block in cad_image.block_entities.values_typed:
block_name = block.name or ""
original_name = block.original_block_name or ""
if (
block_name.lower() == "*model_space"
or original_name.lower() == "*model_space"
):
model_space = block
break
if model_space is None:
raise RuntimeError(
"Model space block was not found."
)
# Create a new TEXT entity
text_entity = CadText()
text_entity.default_value = text_value
text_entity.style_type = "Standard"
text_entity.layer_name = "0"
text_entity.color_id = 256
text_entity.text_height = text_height
text_entity.scale_x = 1.0
# Set text position
text_entity.first_alignment = Cad3DPoint(
text_x,
text_y,
0.0
)
# Add the text to model space
model_space.add_entity(text_entity)
# Update drawing bounds
cad_image.update_size(True)
# Save as editable DXF
dxf_options = DxfOptions()
cad_image.save(str(output_dxf), dxf_options)
print(f"DXF created: {output_dxf}")
# Save as PDF for viewing
raster_options = CadRasterizationOptions()
raster_options.page_width = 1600.0
raster_options.page_height = 1200.0
pdf_options = PdfOptions()
pdf_options.vector_rasterization_options = raster_options
cad_image.save(str(output_pdf), pdf_options)
print(f"PDF created: {output_pdf}")
print("Text added successfully.")
Expected Output
When the script completes successfully, it creates the following files beside sample.dwg:
drawing_with_text.dxf— the exported CAD drawing with the new text entity, where supported by the DXF writer.drawing_with_text.pdf— a rendered copy of the annotated drawing for review or sharing.
The console output is:
DXF created: drawing_with_text.dxf
PDF created: drawing_with_text.pdf
Text added successfully.
Open both output files to confirm that the label is visible and correctly positioned. The original sample.dwg is not modified.
How the Python Code Works
A few details in the example matter when you move from a simple test drawing to a production file.
1. Load and Cast the DWG Drawing
The cad.Image.load() method opens the source file. The example then uses cast(CadImage, image) so that the loaded drawing can be accessed through CAD-specific properties, including block_entities.
The with statement keeps the image open while its entities are modified and exported, then releases the resource when processing finishes.
2. Find the Model-Space Block
A DWG drawing can contain multiple blocks. The new text must be added to the block that represents the intended drawing space.
The example iterates through cad_image.block_entities.values_typed and checks both block.name and block.original_block_name for *Model_Space, ignoring case. This avoids assuming that model space can always be accessed using a direct dictionary key.
If model space cannot be found, the script raises a RuntimeError. This is preferable to silently exporting a file without the new annotation.
3. Create and Position the Text Entity
CadText() creates the new single-line annotation. Its default_value property stores the visible text. The position comes from Cad3DPoint(text_x, text_y, 0.0), assigned to first_alignment.
In this example, text_height = 5.0 defines the height in drawing units, and scale_x = 1.0 sets the horizontal scale factor. The entity uses the Standard text style and layer 0. Its color ID of 256 means ByLayer, so the layer controls its color.
After these properties are set, model_space.add_entity(text_entity) inserts the annotation into model space.
4. Recalculate the Drawing Bounds
Adding text can change the area occupied by drawing content. The call below updates the drawing bounds before export:
cad_image.update_size(True)
The Boolean argument is required by the Python API used in this tested example. Calling update_size() without it can produce a missing-argument error.
5. Export the Annotated Drawing
DxfOptions is used to save the drawing as DXF. CadRasterizationOptions controls the page dimensions for rendering, and PdfOptions produces the PDF file.
Notice that the PDF dimensions are written as 1600.0 and 1200.0, not integers. The tested Python bindings expect numeric values in this form for these setters.
The page dimensions control the export layout; they are not the text height or the drawing’s real-world dimensions.
Change the Text Position, Height, Color, and Style
You can customize a CadText entity by changing its properties before calling add_entity().
| Property | What it controls | Example |
|---|---|---|
default_value | Text shown in the drawing | "VALVE V-101" |
first_alignment | Text position in CAD coordinates | Cad3DPoint(150.0, 80.0, 0.0) |
text_height | Text height in drawing units | 3.0 |
scale_x | Horizontal text scale factor | 1.0 |
style_type | Name of the text style | "Standard" |
layer_name | Layer associated with the text | "0" |
color_id | AutoCAD Color Index value | 1 for red; 256 for ByLayer |
For example, change the text properties in the main script to label a valve:
text_entity.default_value = "VALVE V-101"
text_entity.first_alignment = Cad3DPoint(
150.0, 80.0, 0.0
)
text_entity.text_height = 3.0
text_entity.scale_x = 1.0
text_entity.style_type = "Standard"
text_entity.layer_name = "0"
text_entity.color_id = 1
Run this property-setting snippet before model_space.add_entity(text_entity) in the main example.
Use coordinates that match the actual drawing. CAD drawings often use project-specific units or coordinate systems, so (150, 80) may be inside one drawing and far from the geometry in another. Likewise, a height of 3.0 is not a three-point font size; it is measured in drawing units.
You should also use a text style and layer that exist in the source drawing. The example uses common defaults, but drawings with custom standards may require different names.
Add Multiple Text Labels to a DWG Drawing
Once a single label works, you can extend the same approach to several annotations. This is useful when equipment identifiers, room names, or inspection references are already stored as structured data.
For example, define the labels and their insertion coordinates:
labels = [
("VALVE V-101", 40.0, 80.0),
("VALVE V-102", 70.0, 80.0),
("PUMP P-201", 100.0, 80.0),
("CONTROL PANEL", 130.0, 80.0),
]
for label, x, y in labels:
text = CadText()
text.default_value = label
text.first_alignment = Cad3DPoint(x, y, 0.0)
text.text_height = 2.5
text.scale_x = 1.0
text.style_type = "Standard"
text.layer_name = "0"
text.color_id = 256
model_space.add_entity(text)
cad_image.update_size(True)
Place this snippet inside the with block, after model space is found and before the DXF/PDF exports. It uses the same entity-creation pattern as the working single-text example; the multi-label variation has not been separately tested here.
In a real application, labels could be populated from a CSV file, an equipment register, or a database. The main responsibility of your application is to supply valid coordinates and appropriate text properties. The library inserts the entities at the positions you specify; it does not automatically prevent label overlaps.
Save the Drawing with Text as DXF or PDF
The format you choose depends on what happens after annotation.
Save as DXF for CAD Editing
The main example uses DxfOptions to export the drawing:
dxf_options = DxfOptions()
cad_image.save("drawing_with_text.dxf", dxf_options)
DXF is useful when the next step involves a CAD application or another system that consumes drawing entities. However, Aspose.CAD’s supported-format table describes DXF writing as partially supported. Validate important annotations, layers, and geometry in the exported file before using it in an engineering workflow.
Save as PDF for Viewing and Sharing
For design reviews, reports, or document distribution, the example also exports a PDF:
raster_options = CadRasterizationOptions()
raster_options.page_width = 1600.0
raster_options.page_height = 1200.0
pdf_options = PdfOptions()
pdf_options.vector_rasterization_options = raster_options
cad_image.save("drawing_with_text.pdf", pdf_options)
PDF is intended for viewing the resulting drawing rather than editing its CAD entities. If you need an updated DWG file, use a separate compatible CAD workflow to produce it from an appropriate intermediate format; direct DWG saving is not listed for the Python API.
Troubleshooting Text Insertion in DWG Files
The inserted text is not visible. Check the text coordinates first. The label may have been placed outside the visible geometry. Also inspect the layer’s visibility, the text height, and the selected text style. Compare the DXF and PDF outputs to identify whether the issue occurs during entity insertion or rendering.
The script cannot find model space. The example raises Model space block was not found. if neither block name matches *Model_Space. Inspect the blocks in the source file and confirm that it contains model-space data in the expected structure. Do not continue with a missing block reference.
update_size() reports a missing argument. Use cad_image.update_size(True) as shown in the working example. This signature is important for the Python binding used here.
PDF page dimensions trigger a type error. Pass floating-point values such as 1600.0 and 1200.0 to page_width and page_height, respectively.
The text looks different from the CAD editor. Check the drawing’s text style and whether the corresponding fonts are available in the processing environment. Rendering may differ if the expected font is missing or substituted.
The DXF contains unexpected differences. DXF writing is only partially supported. Test with representative drawings and review the resulting entities in a CAD viewer before integrating the output into an automated process.
Frequently Asked Questions
Can I add text to a DWG file with Python without AutoCAD?
Yes. Aspose.CAD for Python via .NET can load a DWG drawing and add a CadText entity without AutoCAD. The example then exports the modified drawing to DXF and PDF.
How do I specify the position of text in a DWG drawing?
Set first_alignment on the CadText object using Cad3DPoint(x, y, z). Choose values that correspond to a suitable location in the original drawing.
Can I add text to a specific layer?
Yes. Set layer_name to the name of the intended layer. In the main example, the annotation uses layer 0 and color ID 256 (ByLayer).
Can I add multiple text labels automatically?
Yes. Create a new CadText entity for each label, set its content and coordinates, and add it to model space. This pattern can be driven by a list of records or another structured data source.
Can I save the modified drawing back to DWG?
Direct DWG saving is not listed in the Aspose.CAD for Python supported formats. The tested workflow exports the modified drawing to DXF and PDF, leaving the source DWG unchanged.
Get a Free Temporary License
You can request a free 30-day temporary license to evaluate Aspose.CAD for Python via .NET without evaluation restrictions. To apply the license in your Python application, follow the Aspose.CAD licensing guide.
Free Learning Resources
Explore these resources for more information about processing CAD drawings in Python:
- Aspose.CAD for Python Developer Guide – Learn how to load and process CAD files.
- Aspose.CAD Python API Reference – Review classes, properties, and methods used in the examples.
- Work with Text in CAD Drawings – Learn about CAD text-bearing entity types.
- Supported CAD File Formats – Confirm available input and output formats.
- Free Online CAD Applications – View or convert CAD files using browser-based tools.
- Aspose.CAD Support Forum – Ask questions about specific drawings or API behavior.
Conclusion
Adding text to a DWG drawing using Python is a practical way to generate equipment labels, room identifiers, and other annotations from application data. The essential steps are to locate model space, create a CadText entity with appropriate coordinates and styling, and update the drawing bounds before export.
The next step is to replace the example label with coordinates and identifiers from your own drawing data. Verify the DXF output in a CAD editor and use the PDF as a review copy, especially when deploying the workflow across drawings with different units, layers, or fonts.
