Wednesday, November 2, 2016

Extract AutoCAD Civil3D's Label Text

I have been doing much less writing on my AutoCAD programming during past 2 years, because of a). I have been quite busy at work, thus much less time I can spend on the topics I might have interest to dig in; 2). since I became master marathon runner (in my late 50!) a couple years ago, most my out-of-work time has been running, endless running (50 to 70 km/week, 4 to 6 formal races/year).

Anyway, back to AutoCAD programming. My company moved from AutoCAD Map to AutoCAD Civil3D since AutoCAD 2015 a while ago. Naturally, some custom programming task against AutoCAD Civil3D features became my job description, which exposes me to a vast new realm that I did not touch before.

Recently, I was ask to provide a way to extract Civil3D label's text. Labels in Civil3D are very powerful and complicated annotation objects. As a "newbie" Civil3D programmer, I spent quite sometime in vain to search through Civl3D's API: nothing came up to let me retrieve the displayed text string of a label.

Eventually, I found this article "Get CogoPoint Label Text" in ADN blogs "Infrastructure Modeling DevBlog", by Augosto Goncalves.

The code shown in that article worked quite well, except that if a label's text is stacked (e.g. the label text is displayed as multiple lines of text), there would be missing space between the text string segment. See this video clip.

The "missing space" issue can be easily fixed by adding a space when retrieved text string segment being combined with previously retrieved text string segment. See the the code below, which is quoted from that article with minor modification (in red):

private string GetText(ObjectId id)
    // store the DBTexts
    StringBuilder entityText = new StringBuilder();
    Database db = Application.DocumentManager.
    using (Transaction trans = db.
        // open the entity
        Entity point = trans.GetObject(id,
            OpenMode.ForRead) as Entity;
        // do a full explode (considering explode again
        // all BlockReferences and MText)
        List<DBObject> objs = FullExplode(point);
        foreach (Entity ent in objs)
            // now get the text of each DBText
            if (ent.GetType() == typeof(DBText))
                DBText text = ent as DBText;
                entityText.AppendLine(" " + text.TextString);
    return entityText.ToString().Trim();

See this video clip showing the result of modified code. I was quite happy of adopting this code in my work to allow my program retrieve Civil3D label's displayed text, well, until I ran into "curved" labels (e.g. labels used to annotate curved line work, in which the text characters are aligned along the curve) - all the spaces between text segment that make the text string read-able were gone. Actually, when running my modified code shown above, a space added between every character of the label text.

See this video clip showing the result of retrieved label text on "curved" label.

To investigate the cause, I manually did the recursive exploding of a label, as the code does, either a straight one, or curved one. The manual exploding revealed:

  • With straight label, after recursive exploding I end up with one or more DBText entities. Thus, I can combine all the DBTexts' TextString value with space in between to eventually  assemble a text string as the label's displayed text.
  • With curved string, after the recursively exploding, the label is also eventually exploded into DBText entities with each single character as a DBText, thus the resulted DBTexts effectively lose their literal meaning.
I have to say that whoever created Civil3D label, he/she must be incredibly talented and invented the way to use curved label to annotate curved entities. But how do I get the labels displayed text, so that it still conveys the same literal meaning as the label? 

It turned out a solution came out rather easily when I discuss the difficulty I was facing (with the curved label) with an experienced Civil3D user, showing how a label ends up with after repeated explode. He suggests I drag the curved label first before the attempt of retrieving label text, because dragging a curved label makes it "straight" label. So, the solution is programmtically dragging the label, retrieving the label text with recursive exploding, and then placing the dragged label back (resetting the label).

Here is the code I wrote, based Augosto's, which drags a curved label before exploding it in memory, and then place the label back (to curved style):

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using CivilDb = Autodesk.Civil.DatabaseServices;
namespace WSP.GEO.UDS.Civil3dUtilities
    public static class LabelTextExtractor
        public static string GetDisplayedLabelText(CadDb.ObjectId labelId)
            if (labelId.ObjectClass.DxfName.ToUpper()!="AECC_GENERAL_SEGMENT_LABEL")
                throw new ArgumentException(
                    "argument mismatch: not an \"AECC_GENERAL_SEGMENT_LABEL\"");
            StringBuilder lblText = new StringBuilder();
            using (var tran=labelId.Database.TransactionManager.StartTransaction())
                var label = tran.GetObject(labelId, OpenMode.ForRead) as CivilDb.Label;
                if (label!=null)
                    bool changed = !label.Dragged && label.AllowsDragging;
                        if (changed)
                            double delta = label.StartPoint.DistanceTo(label.EndPoint);
                            label.LabelLocation = 
                                new Point3d(label.LabelLocation.X + 
                                    delta, label.LabelLocation.Y + 
                                    delta, label.LabelLocation.Z);
                        var dbObjs = FullExplode(label);
                        foreach (var obj in dbObjs)
                            if (obj.GetType() == typeof(DBText))
                                lblText.Append(" " + (obj as DBText).TextString);
                        if (changed) label.ResetLocation();
            return lblText.ToString().Trim();
        #region private methods
        private static List<CadDb.DBObject> FullExplode(CadDb.Entity ent)
            // final result
            List<CadDb.DBObject> fullList = new List<CadDb.DBObject>();
            // explode the entity
            DBObjectCollection explodedObjects = new DBObjectCollection();
            foreach (CadDb.Entity explodedObj in explodedObjects)
                // if the exploded entity is a blockref or mtext
                // then explode again
                if (explodedObj.GetType() == typeof(CadDb.BlockReference) ||
                    explodedObj.GetType() == typeof(CadDb.MText))
            return fullList;

As the code shows, I do not even care if the label is straight or curved. I simply test if the label is allowed to be dragged and if yes, if being dragged. If both are yes, programmatically drag it before doing the recursive explodes. Afterwards, I rest the label's location, if it has been programmatically dragged.

Here is the video clip showing the result of retrieving label's text.


Neha Mahto said...

Very fruitful post you have, keep sharing like this...
SAP BPC Training | SAP MM Online Training

Mirro87 said...

Man you solved it better then i did hehe i used select previous and then explode manually and then used my program to get info from Label. Thanks for this!!!


About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.