Jump to content

Python, Extract Polyline Lengths with Associated Text Labels in AutoCAD


Recommended Posts

Posted

sample of this

 

import traceback
from pyrx import Db, Ed, Ge, Ap, Rx, Gs


@Ap.Command()
def doit():
    try:
        # select
        db = Db.curDb()
        filter = [(Db.DxfCode.kDxfStart, "TEXT,LWPOLYLINE")]
        ps, ss = Ed.Editor.select(filter)
        if ps != Ed.PromptStatus.eOk:
            raise RuntimeError("Selection Error! {}: ".format(ps))
        texts = [Db.Text(id) for id in ss.objectIds(Db.Text.desc())]
        plines = [Db.Polyline(id) for id in ss.objectIds(Db.Polyline.desc())]

        # make kdtree & list of points
        pntmap = {}
        plpoints = []
        for pl in plines:
            plpoints.append(pl.getStartPoint())
            plpoints.append(pl.getEndPoint())
            pntmap[pl.getStartPoint()] = pl
            pntmap[pl.getEndPoint()] = pl

        # search closest pline
        results = []
        tree = Ge.Point3dTree(plpoints)
        for text in texts:
            idxs, _ = tree.knnSearch(text.position(), 1)
            pl: Db.Polyline = pntmap[plpoints[idxs[0]]]
            results.append([text.textString(), pl.getDistAtParam(pl.getEndParam())])

        # format mtext
        results = sorted(results, key=lambda x: int(x[0][2:]))
        buffer = "{:<6}\t{}\\P".format("S.No", "Length Ft")
        buffer += "".join(f"{sno:<6}\t  {plen:>.2f}\\P" for sno, plen in results)

        # make mtext, add to currentSpace
        ps, pnt = Ed.Editor.getPoint("\nPick Text Position")
        mt = Db.MText()
        mt.setDatabaseDefaults(db)
        mt.setLocation(pnt)
        mt.setContents(buffer)
        cs = db.currentSpace(Db.OpenMode.kForWrite)
        cs.appendAcDbEntity(mt)

    except Exception as err:
        traceback.print_exception(err)

 

our.png.dce00c082023db3ec790bec133e4c259.png

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...