Work with text
Work with text
Almost all drawings contain text objects and these examples show how to perform operations with them. There are different types of entities for DWG/DXF that can store text, they are CadText, CadMText, CadAttDef, CadAttrib. Two last types are typically related to CadInsertObject and stored inside it or in the corresponding block.
Here are some examples describing operations with text.
Search for the text
This example shows how to find text values in the DWG/DXF file and may be used also for replacing of text values.
using (CadImage cadImage = (CadImage)Image.Load(fileName)) | |
{ | |
foreach (CadBaseEntity entity in cadImage.Entities) | |
{ | |
if (entity.GetType() == typeof(CadText)) | |
{ | |
CadText text = (CadText)entity; | |
System.Console.WriteLine(text.DefaultValue); | |
} | |
if (entity.GetType() == typeof(CadMText)) | |
{ | |
CadMText mtext = (CadMText)entity; | |
System.Console.WriteLine(mtext.FullClearText); | |
} | |
if (entity.GetType() == typeof(CadAttrib)) | |
{ | |
CadAttrib attrib = (CadAttrib)entity; | |
System.Console.WriteLine(attrib.DefaultText); | |
} | |
if (entity.GetType() == typeof(CadAttDef)) | |
{ | |
CadAttDef attdef = (CadAttDef)entity; | |
System.Console.WriteLine(attdef.DefinitionTagString); | |
} | |
if (entity.TypeName == CadEntityTypeName.INSERT) | |
{ | |
CadInsertObject insert = (CadInsertObject)entity; | |
CadBlockEntity block = cadImage.BlockEntities[insert.Name]; | |
foreach (CadBaseEntity blockEntity in block.Entities) | |
{ | |
if (blockEntity.GetType() == typeof(CadAttDef)) | |
{ | |
CadAttDef attdef = (CadAttDef)blockEntity; | |
System.Console.WriteLine(attdef.PromptString); | |
} | |
} | |
foreach (CadBaseEntity e in insert.ChildObjects) | |
{ | |
if (e.TypeName == CadEntityTypeName.ATTRIB) | |
{ | |
CadAttrib attrib = (CadAttrib)e; | |
System.Console.WriteLine(attrib.DefinitionTagString); | |
} | |
} | |
} | |
} | |
} |
Adding new Text and MText items
Here is the example how to add new Text/Mtext objects to the drawing. Addition of new entities may change size of the drawing, so it is recommended to call UpdateSize() after these operations.
// adding of Text | |
CadText text = new CadText(); | |
text.DefaultValue = "Watermark text"; | |
text.TextHeight = 40; | |
text.FirstAlignment = new Cad3DPoint(300, 40); | |
text.LayerName = "0"; | |
cadImage.BlockEntities["*Model_Space"].AddEntity(text); | |
cadImage.UpdateSize(); | |
// adding of Mtext | |
CadMText watermark = new CadMText(); | |
watermark.Text = "Watermark message"; | |
watermark.InitialTextHeight = 40; | |
watermark.InsertionPoint = new Cad3DPoint(300, 40); | |
watermark.LayerName = "0"; | |
cadImage.BlockEntities["*Model_Space"].AddEntity(watermark); | |
cadImage.UpdateSize(); |