Tuesday, March 26, 2024

TraceBoundary sample in Python for AutoCAD

 

 

import traceback
from pyrx_imp import Rx
from pyrx_imp import Ge
from pyrx_imp import Gi
from pyrx_imp import Db
from pyrx_imp import Ap
from pyrx_imp import Ed
from pyrx_imp import Gs

def PyRxCmd_TB() -> None:
    try:
        db = Db.curDb()
        prtes = Ed.Editor.getPoint("\nPick a point")
        if prtes[0] != Ed.PromptStatus.eOk:
            return
       
        for pline in Ed.Editor.traceBoundary(prtes[1], False):
            pline.setColorIndex(1)
            db.addToCurrentspace(pline)
           
    except Exception as err:
        traceback.print_exception(err)



 

 

Saturday, February 24, 2024

How to make a Revcloud in Python for AutoCAD

 

There isn’t a “revcloud” entity type in Autocad, but you can make one with a polyline and enlisting the help of send command.  Here’s the sample code

 

import traceback
import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed

import AxApp24 as Ax

def PyRxCmd_doit() -> None:
    try:
        # get the app, doc and model space
        axApp = Ax.getApp()
        doc = axApp.ActiveDocument
        ms = doc.ModelSpace

        # coords for the cloud and create a polyline
        coords = [0, 0, 0, 0, 1000, 0, 1000, 1000, 0, 1000, 0, 0, 0, 0, 0]
        pl = ms.AddPolyline(coords)
       
        #use send command to create the revcloud, note the (A)arc length
        handle = '(handent "{}")'.format(pl.Handle)
        doc.SendCommand("revcloud A {} Object {} Y ".format(200, handle))

    except Exception as err:
        traceback.print_exception(err)


 

And the result:

 


Sunday, December 10, 2023

Python for AutoCAD, Using shapely to find an oriented bounding box.

 

I see this asked frequently in the AutoCAD forums “How do I get the bounding box of an entity”, and the standard answer is usually, “Use vla-GetBoundingBox”, or get the entity extents. This is the correct answer, caveat, the bounding box is aligned with WCS, so if your object is rotated the result may not be what you need.

 One option is to transform the object to align with WCS. Or we can use a 3rd party tool like Python’s shapely to help. 

 

here's an example:

import traceback
import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed

from shapely import LineString

def PyRxCmd_doit():
    try:
       
        #create a selection set filter and select the polylines
        filter = [(Db.DxfCode.kDxfStart, "LWPOLYLINE")]
       
        ss = Ed.Editor.selectPrompt(
            "\nSelect parts: ", "\nRemove parts: ", filter)

        if ss[0] != Ed.PromptStatus.eNormal:
            return

        #iterate the selection set
        for id in ss[1].objectIds():
           
            #create a LineString from our polylines
            pline = Db.Polyline(id)
            ls = LineString(pline.toList())
           
            #get the oriented bbox
            coords = ls.oriented_envelope.exterior.coords
           
            #convert tuples to Ge.Point3d
            points = [Ge.Point3d(p) for p in coords]
           
            # #draw the results
            Ed.Core.grDraw(points[0], points[1],1,0)
            Ed.Core.grDraw(points[1], points[2],1,0)
            Ed.Core.grDraw(points[2], points[3],1,0)
            Ed.Core.grDraw(points[3], points[0],1,0)

    except Exception as err:
        traceback.print_exception(err)


 


 


 

Saturday, December 9, 2023

Web Scrape to a BricsCAD table using Python and PyRx

 

I thought this interesting. I could imagine using python to scrape some industry specific data, maybe a spec sheet or a materials list into a Table. Possibly a useful tool for importing “DATA” into a drawing.

 This example uses BeautifulSoup, Requests and Pandas

 

import traceback
import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd


# sample source https://www.scraperapi.com/blog/python-loop-through-html-table/
def scraper9000():
    url = "https://datatables.net/examples/styling/stripe.html"
    response = requests.get(url)
    soup = bs(response.text, "html.parser")
    table = soup.find("table", class_="stripe")
   
    data = {
        'Name': [],
        'Position': [],
        'Office': [],
        'age': [],
        'Start date': [],
        'salary': [],
    }
    for employee_data in table.find_all("tbody"):
        for row in employee_data.find_all("tr"):
            data['Name'].append(row.find_all("td")[0].text)
            data['Position'].append(row.find_all("td")[1].text)
            data['Office'].append(row.find_all("td")[2].text)
            data['age'].append(row.find_all("td")[3].text)
            data['Start date'].append(row.find_all("td")[4].text)
            data['salary'].append(row.find_all("td")[5].text)
           
    return data


def PyRxCmd_doit():
    try:
        db = Db.curDb()
        df = pd.DataFrame(scraper9000())
 
        table = Db.Table()
        table.setDatabaseDefaults(db)
 
        # add one for the title and header
        table.setSize(df.shape[0]+2, df.shape[1])
 
        #title
        table.setTextString(0, 0, "Scrape Master 9000")
       
        headers = df.columns.values.tolist()
        datas = df.values.tolist()
 
        for col, value in enumerate(headers):
            table.setTextString(1, col, "{}".format(value))
 
        for row, data in enumerate(datas):
            for col, value in enumerate(data):
                table.setTextString(row+2, col, "{}".format(value))
 
        model = Db.BlockTableRecord(db.modelSpaceId(), Db.OpenMode.kForWrite)
        model.appendAcDbEntity(table)
 
    except Exception as err:
        traceback.print_exception(err)




 



TraceBoundary sample in Python for AutoCAD

    import traceback from pyrx_imp import Rx from pyrx_imp import Ge from pyrx_imp import Gi from pyrx_imp import Db from pyrx_imp...