Saturday, October 7, 2023

Export Blocks to DWG with Python for AutoCAD

 

Here’s a sample of exporting blocks to files using PyRx.  The main idea here is to filter the blocks we want to export, then use Database::wblock to create a new database, we can then save as the file format we want

 

# import
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 traceback

# define command blkstoDWG
def PyRxCmd_blkstoDWG():
    try:
        db = Db.curDb()
        exportBlock(db,'E:\\temp\\','dwg' )
    except Exception as err:
        traceback.print_exception(err)
           
# define command blkstoDXF
def PyRxCmd_blkstoDXF():
    try:
        db = Db.curDb()
        exportBlock(db,'E:\\temp\\','dxf' )
    except Exception as err:
        traceback.print_exception(err)
       
# use wblock to create a new database from the block id
def exportBlock(db, path, ext)->bool:
    bt = Db.BlockTable(db.blockTableId())
    for name, id in bt.toDict().items():
        if not checkBlock(name, id):
            continue
        outDb = db.wblock(id)
        if ext.casefold() == "dxf".casefold():
            outDb.dxfOut("{}{}.{}".format(path,name,ext))
        if ext.casefold() == "dwg".casefold():
            outDb.saveAs("{}{}.{}".format(path,name,ext))

# filter out the blocks we don't want
def checkBlock(name, id)->bool:
    btr = Db.BlockTableRecord(id)
    if btr.isLayout():
        return False
    if btr.isAnonymous():
         return False
    if btr.isFromExternalReference():
        return False
    if btr.isFromOverlayReference():
        return False
    if(name.startswith("A$")):
        return False
    return True
       
       

       


 


No comments:

Post a Comment

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...