#!/usr/bin/env python # -*- coding: utf-8 -*- from pyautocad import Autocad, APoint from pyautocad.contrib.tables import Table acad = Autocad() p1 = APoint(0, 0) for i in range(5): obj = acad.model.AddText(u'Hi %s!' % i, p1, 2.5) p1.y += 10 table = Table() for obj in acad.iter_objects('Text'): x, y, z = obj.InsertionPoint table.writerow([obj.TextString, x, y, z]) table.save('data.xls', 'xls') data = Table.data_from_file('data.xls')
def Auto_Mark(self): # 连接CAD acad = Autocad(create_if_not_exists=True) # 设定变量 for leader in acad.iter_objects('Leader'): leader.DimensionLineColor = 2 for dim in acad.iter_objects('Dimension'): attribute = dir(dim) dim.TextColor = 2 dim.DimensionLineColor = 2 dim.ExtensionLineColor = 2
class DrawCAD: def __init__(self): self.acad = Autocad( create_if_not_exists=True) # so far app is not open self.dimscale = 100 # annotative scale for sizes #TODO масштаб должен настраиваться автоматически print("AutoCad запущен. Создан документ", self.acad.doc.Name) self.acad.Application.Documents.open( "d:\Picture_ENG.dwg") #TODO путь с пробелами вызывает трудности print(self.acad.doc.Name) self.acad.size_scale( self.dimscale) # setting annotative scale for sizes self._clear() #стирание из файла def _clear(self): #TODO убрать костыль так, чтобы удаление не вызывало исключений while True: try: for obj in self.acad.iter_objects(): obj.Delete() break except Exception: print( "Exception: ошибка при удалении. Выход из исключения, продолжение работы" ) continue def _drawLabel(self, shape): #TODO в зависимости от ориентации блока, вывести текст в середине print(shape.label) #drawing shapes consisting of points def _drawOverallDim(self, shape): #connecting all points of overall dimensions num = len(shape.points["overallDim"]) for i in range(num - 1): self.acad.model.AddLine(shape.points["overallDim"][i], shape.points["overallDim"][i + 1]) # to close the shape self.acad.model.AddLine(shape.points["overallDim"][num - 1], shape.points["overallDim"][0]) # draw overall sizes: horizontal and vertical #TODO проверить работу простановки размеров на повернутых объектах self._drawSize(shape.points["overallDim"][0], shape.points["overallDim"][1], 2000) self._drawSize(shape.points["overallDim"][0], shape.points["overallDim"][3], 1000) # drawing size btw 2 points and with defined indent def _drawSize(self, p1, p2, indent): self.acad.linear_size(p1.x, p1.y, p2.x, p2.y, indent) def draw(self, shape): self._drawOverallDim(shape)
def test1(): #Test1: mesh testing acad = Autocad() acad.prompt("Hello, Autocad from Python\n") print acad.doc.Name p1 = APoint(0, 0) p2 = APoint(50, 25) for i in range(5): text = acad.model.AddText('Hi %s!' % i, p1, 2.5) acad.model.AddLine(p1, p2) acad.model.AddCircle(p1, 10) p1.y += 10 dp = APoint(10, 0) for text in acad.iter_objects('Text'): print('text: %s at: %s' % (text.TextString, text.InsertionPoint)) text.InsertionPoint = APoint(text.InsertionPoint) + dp for obj in acad.iter_objects(['Circle', 'Line']): print(obj.ObjectName)
import pyautocad from pyautocad import Autocad, APoint cad = Autocad() cad.prompt("hello") for text in cad.iter_objects("AcDbText"): print(text.TextString, text.InsertionPoint) dim_list = [] for dim_obj in cad.iter_objects("AcDbRotatedDimension"): dim_name_all = dim_obj.TextOverride dim_name_split = dim_name_all.split(" ") dim_name = dim_name_split[1].rstrip(":}<>") dim = int(dim_obj.Measurement) dim_dic = {dim_name: dim} dim_list.append(dim_dic) print(dim_list)
def autocadsign(atype,filedirection,linedata,datedata=None,atype_date=None,Height=None): if atype_date==None: atype_date=' ' if Height==None: Height=[400,300] # linedata[0]=[[x1,x2],[y1,y2]] movesize=[int(linedata[0][0][0]),int(linedata[0][1][0])] #1:100 move toward right is positive atype_movesize=[int(linedata[0][0][1]),int(linedata[0][1][1])] signloc=[] for i in linedata[1]: signloc.append(int(i)-1) # 标准1:100图框,五个模式分别对应五个位置 if datedata: mode1={'A3':(30150,3420),'A2':(47080,3920),'A1':(71560,3920),'A0':(106580,3920)} mode2={'A3':(25460,1320),'A2':(42580,1820),'A1':(67060,1820),'A0':(101850,1820)} mode3={'A3':(25460,2020),'A2':(42580,2520),'A1':(67060,2520),'A0':(101850,2520)} mode4={'A3':(25460,2720),'A2':(42580,3220),'A1':(67060,3220),'A0':(101850,3220)} mode5={'A3':(25460,3420),'A2':(42580,3920),'A1':(67060,3920),'A0':(101850,3920)} else: mode1={'A3':(30450,3420),'A2':(47380,3920),'A1':(71860,3920),'A0':(106880,3920)} mode2={'A3':(25760,1320),'A2':(42880,1820),'A1':(67360,1820),'A0':(102150,1820)} mode3={'A3':(25760,2020),'A2':(42880,2520),'A1':(67360,2520),'A0':(102150,2520)} mode4={'A3':(25760,2720),'A2':(42880,3220),'A1':(67360,3220),'A0':(102150,3220)} mode5={'A3':(25760,3420),'A2':(42880,3920),'A1':(67360,3920),'A0':(102150,3920)} atype_mode1 = {'A3': (34000, 8150), 'A2': (50900, 8650), 'A1': (75600, 8650), 'A0': (110400, 8650)} atype_mode2 = {'A3': (35500, 8150), 'A2': (52400, 8650), 'A1': (77100, 8650), 'A0': (111900, 8650)} atype_mode3 = {'A3': (37000, 8150), 'A2': (53900, 8650), 'A1': (78600, 8650), 'A0': (113400, 8650)} atype_mode4 = {'A3': (38500, 8150), 'A2': (55400, 8650), 'A1': (80100, 8650), 'A0': (114900, 8650)} atype_mode5 = {'A3': (40000, 8150), 'A2': (56900, 8650), 'A1': (81600, 8650), 'A0': (116400, 8650)} middlemode=[mode1,mode2,mode3,mode4,mode5] atype_middlemode=[atype_mode1,atype_mode2,atype_mode3,atype_mode4,atype_mode5] number=len(signloc) mode=[] atype_mode=[] filepath=[] for i in range(number): filepathloc=os.path.join(filedirection,'signfile\\'+linedata[2][i]+".dwg") filepath.append(filepathloc) mode.append(middlemode[signloc[i]]) atype_mode.append(atype_middlemode[signloc[i]]) acad = Autocad(create_if_not_exists=False) acad.prompt("Hello, Autocad\n") # print(acad.doc.Name) Layerobj = acad.ActiveDocument.Layers.Add("CADSIGN") if atype: acad.ActiveDocument.ActiveTextStyle = acad.ActiveDocument.TextStyles.Item('standard') acad.ActiveDocument.ActiveLayer = Layerobj data=[] for block in acad.iter_objects('Block'): blockname=block.name[0:2] if blockname in ['A0','A1','A2','A3']: data.append((blockname,block.InsertionPoint[0],block.InsertionPoint[1],block.XScaleFactor)) cadnumber=len(data) for i in range(number): for j in range(cadnumber): block=data[j][0] scale=data[j][3]/100 # data[j]是图框的左下角坐标 # mode[i]是哪个位置的签名,block是每个图框下需要移动的位置 x=data[j][1]+(mode[i][block][0]+movesize[0])*scale y=data[j][2]+(mode[i][block][1]+movesize[1])*scale p1=APoint(x,y) acad.model.InsertBlock(p1, filepath[i], scale,scale,scale, 0) if datedata: x2=x+1200*scale p2=APoint(x2,y) acad.model.AddText(datedata[i],p2,200*scale) if atype: x3=data[j][1]+(atype_mode[i][block][0]+400+atype_movesize[0])*scale y3=data[j][2]+(atype_mode[i][block][1]+atype_movesize[1])*scale p3=APoint(x3,y3) x4=x3-100*scale y4=y3-400*scale p4=APoint(x4,y4) # linedata[2]是需要签名的名字 acad.model.AddText(NAMETABLE_REVERSE[linedata[2][i]], p3, Height[0]* scale) acad.model.AddText(atype_date, p4, Height[1] * scale) acad.prompt("Autosign Successfully\n")
try: acad.ActiveDocument.Application.Documents.Open("C:\\Users\\PeterZhu\\Desktop\\AutoCAD_Source\\SH-TL101823-DET-%d-001.dwg"%(i)) except: part_num = False elif i<=9: try: acad.ActiveDocument.Application.Documents.Open("C:\\Users\\PeterZhu\\Desktop\\AutoCAD_Source\\SH-TL101823-DET-00%d-001.dwg"%(i)) except: part_num = False #如果存在此零件号 if part_num: print("Open Part No%d"%(i)) #获取MREVBLK块的对角线坐标 for obj in acad.iter_objects("AcDbBlockReference"): if obj.Name == "MREVBLK": Point_Lower_Left=obj.GetBoundingBox()[0] Point_Upper_Right=obj.GetBoundingBox()[1] #获得MREVBLK边界对角线点的坐标 LL=APoint(Point_Lower_Left) UR=APoint(Point_Upper_Right) UL=APoint(LL.x,UR.y) LR=APoint(UR.x,LL.y) print ("Block Coordinate Read") #确定文字位置和大小的缩放比例 Length=UL.y-LL.y Scale=Length/92.07500000000059
from pyautocad import Autocad, APoint acad = Autocad() acad.prompt("Hello, Autocad from Python\n") #raise print(acad.doc.Name) p1 = APoint(0, 0) p2 = APoint(50, 25) for i in range(5): text = acad.model.AddText('Hi %s!' % i, p1, 2.5) acad.model.AddLine(p1, p2) acad.model.AddCircle(p1, 10) p1.y += 10 for text in acad.iter_objects('Text'): print("H") # dp = APoint(10, 0) # for text in acad.iter_objects('Text'): # print('text: %s at: %s' % (text.TextString, text.InsertionPoint)) # text.InsertionPoint = APoint(text.InsertionPoint) + dp # # for obj in acad.iter_objects(['Circle', 'Line']): # print(obj.ObjectName)
pass else: #画弧 pass def draw_block(model=None): model_info=model.draw_info line_info=model_info[0] wenzi_info=model_info[1] arc_info=model_info[2] block_start_point = APoint(0, 0) blockObj = acad.ActiveDocument.Blocks.Add(block_start_point, wenzi_info[0]) draw_line(blockObj,line_info) draw_wenzi(blockObj,wenzi_info) draw_arc(blockObj,arc_info) block_info.append(wenzi_info[0]) def place_block(place_info,block_info): for insertionPnt,load_name in zip(place_info,block_info): acad.model.InsertBlock(insertionPnt, load_name, 1, 1, 1, 0) draw_block(model=l1) draw_block(model=l2) draw_block(model=l3) place_info=[APoint(0,0),APoint(1100,0),APoint(0,600)] place_block(place_info,block_info) for obj in acad.iter_objects("Block"): # 以下获取块的属性信息 # 如果想获取某一特定块的属性信息可以用ObjectID识别特定块 print(obj.ObjectName) # print(dir(obj))
from pyautocad import Autocad, APoint import math PI = math.pi acad = Autocad('Test.dwg') for dim in acad.iter_objects('Dimension'): print(dim.EntityName, dim.EntityType) print(dim.GetTypeInfo) print(dim.Handle.title()) print(dim.TextPosition) if dim.EntityType == 10: print(round(dim.Measurement * 180 / PI, 3)) else: print(dim.Measurement) print('==============================\n')
class drawDWG: def __init__(self): self.path2dwg = "" self.data = {} path = "Files/templates.json" # путь до JSON файла self.templates = self._getTemplates(path) def _getTemplates(self, path): with open(path, 'r', encoding="utf-8") as f: templates = json.loads(f.read()) return templates def _defineLayers(self): layers = dict() for key in self.templates["Layers"].keys(): print(key) newLayer = self.acad.doc.Layers.Add(key) # добавить новый слой newLayer.Color = self.templates["Layers"][key]["color"] # смена цвета выбранного слоя. Все цвета описаны здесь: http://help.autodesk.com/view/ACD/2016/ENU/?guid=GUID-D08F9A8E-5551-4473-A270-D95F7F32F51A layers.update({key : newLayer}) return layers def _activate_layer(self, name_layer): self.acad.doc.ActiveLayer = self.layers[name_layer]# выбор текущего слоя def execute(self, data): #self.data = copy.deepcopy(data) self.data = data self.scale = self._getScale()#scale содержит гостовский масштаб self.scaledCellSize = self.scale * self.data["CellSize"] self.cells = Cells(self.scaledCellSize, self.data["Radius"] * self.scale) # содержит блоки-конструктор для отрисовки конвейера self.acad = Autocad(create_if_not_exists=True) # so far app is not openw self.acad.app.Documents.Open(os.getcwd() + "/Files/AutoCAD_templates/А1.dwg") self.acad.ActiveDocument.SaveAs(tempfile.gettempdir() + "/name.dwg") #TODO вписать имя из словаря data self.layers = self._defineLayers() self.pathQmax = "D:\YandexDisk\#SKOLTECH\Early Research Tecnomax\pythonScript\Files\AutoCAD_cabines\Q-MAX.dwg" # TODO create windows attention about that in that time autocad will be opening #self.acad.Application.Documents.open(self.pathQmax) """l = [] for obj in self.acad.iter_objects(): try: if obj.layer == "Границы Цеха": l.extend(list(obj.coordinates)) #use extend because will be 1 list except Exception: print(f"Exception: ошибка при итерации по файлу {self.path2dwg}") continue """ #self.acad.Application.Documents.Add() self._conveyorsDraw() self._scaleFigures() self._figuresDraw() #x = input() #ошибка возникает дальше при вызове канваса return "done" # функция для оппределения scale фактора для чертежа. Задача: поместить полученную расстановку в заданый формат # пока формат только А1 # TODO добавить поддержку остальных форматов def _getScale(self): index = self.data["occupiedFrame"].index(max(self.data["occupiedFrame"]))#если 0, то ширина расстановки самая большая сторона, иначе высота key = ["width", "height"] scale_raw = self.templates["A1"][key[index]] / self.data["occupiedFrame"][index] / self.data['CellSize'] #перевод стандартных масштабов во float-список scales = [float(e.split(":")[0]) / float(e.split(":")[1]) for e in self.templates["GHOSTscales"]] #выбираю подходящий стандартный мастшаб из гостовских масштабов уменьшения for scale in scales: if scale > scale_raw: continue else:#возвращаю подходящий гостовский масштаб и строку return scale #масштабирование фигур с заданым масштабом def _scaleFigures(self): for i, f in enumerate(self.data["Figures"]): coord = f.start_point self.data["Figures"][i].start_point = Coordinate(coord.x * self.scaledCellSize, coord.y * self.scaledCellSize) coord = f.finish_point self.data["Figures"][i].finish_point = Coordinate(coord.x * self.scaledCellSize, coord.y * self.scaledCellSize) # отрисовка основной надписи. Размер листа пока А1 def _templateDraw(self): # insPoint = self.acad.insertionPnt(0,0,0) self.acad.model.InsertBlock([0, 0, 0], "D:\YandexDisk\#SKOLTECH\Early Research Tecnomax\pythonScript\Files\AutoCAD_cabines\qmax.dwg", 1, 1, 1, 0) pass # отрисовка фигур в натуральную величину def _getFigures(self): offset = self.templates["CoordSys"] figures = copy.deepcopy(self.data["Figures"]) for f in figures: f.start_point += Coordinate(offset[0], offset[1]) f.finish_point += Coordinate(offset[0], offset[1]) return figures def _figuresDraw(self): self._activate_layer("blocks") figures = self._getFigures() points = list() for f in figures: p = [f.start_point.y, -f.start_point.x, (f.finish_point.y + self.scaledCellSize), -f.start_point.x, (f.finish_point.y + self.scaledCellSize), -(f.finish_point.x + self.scaledCellSize), f.start_point.y, -(f.finish_point.x + self.scaledCellSize), f.start_point.y, -f.start_point.x] self.acad.model.AddLightWeightPolyline(array.array("d", p)) insert_point = APoint(f.start_point.y + (f.finish_point.y - f.start_point.y + self.scaledCellSize)*0.5, - f.start_point.x -(f.finish_point.x - f.start_point.x + self.scaledCellSize)*0.5) text = self.acad.model.AddText(f.name, insert_point, 5) if (f.finish_point.y - f.start_point.y) < (f.finish_point.x - f.start_point.x): text.rotation = 1.5708 text.Alignment = ACAD.acAlignmentCenter text.TextAlignmentPoint = insert_point # возвращает координаты мнимой клетки def _getImaginaryCell(self, figure, point): if point.y < figure.start_point.y: return Coordinate(point.x, figure.start_point.y)#слева elif point.y >= figure.finish_point.y: return Coordinate(point.x, figure.finish_point.y)#справа elif point.x >= figure.finish_point.x: return Coordinate(figure.finish_point.x - 1, point.y)#снизу elif point.x < figure.start_point.x: return Coordinate(figure.start_point.x, point.y)#сверху def _getFinConv(self, conveyor): if len(conveyor[0]) == 0: return [] finConveyor = copy.deepcopy(conveyor[0]) offset = Coordinate(self.templates["CoordSys"][0], self.templates["CoordSys"][1]) for i in [1,2]: for f in self.data["Figures"]: if conveyor[i] == f.name: figure = f point = conveyor[0][0 if i == 1 else -1] print(point.x, point.y, point) point += offset print(point.x, point.y, point) break if i == 1: finConveyor.insert(0, self._getImaginaryCell(figure, point)) else: finConveyor.append(self._getImaginaryCell(figure, point)) return finConveyor def _getCode(self, coords): self.code = str() for i in [1, 2]: self.code += str(np.sign(coords[i].x - coords[i-1].x)) self.code += str(np.sign(coords[i].y - coords[i-1].y)) return self.code def _conveyorsDraw(self): self._activate_layer("conveyor") self.coded_conveyors = list() self.conveyors = list() # в этом цикле для каждой клетки конвейера получаем код for conv in self.data["Conveyors"]: self.conveyors.append(Conveyor(conveyor)) conveyor = self._getFinConv(conv) #разбиваем конвейер на клеточки for i in range(2, len(conveyor)): self.coded_conveyors.append([self._getCode([conveyor[i-2],conveyor[i-1],conveyor[i]]), conveyor[i-1]]) #TODO сделать в первую очередь преобразование локальных координат в глобальные for cell in self.coded_conveyors: try: cell_draw = self.cells.getCell(cell[0], cell[1]) #TODO передавать список for elem in cell_draw: #if isinstance(cell_draw[0], list) else [cell_draw]: if elem[0] == "line": self.acad.model.AddLightWeightPolyline(array.array("d", elem[1:])) elif elem[0] == "arc": self.acad.model.AddArc(elem[1], elem[2], elem[3], elem[4]) except KeyError: continue #returns coordinate of base point, width and height of each figure on the list def _getBPoint_W_H(self, listCoordinates): maxindexes = [i * 2 + 1 for i, j in enumerate(listCoordinates[1::2]) if j == max( listCoordinates[1::2])] # возвращает индексы максимальных элементов по Y координате ( поэтому я указал отсчет со 2 элемента) minindexes = [i * 2 for i, j in enumerate(listCoordinates[0::2]) if j == min(listCoordinates[0::2])] #теперь находим все минимальные indexbP = [i for i in maxindexes if (i - 1) in minindexes] # find index of Y of base Point indexbP = [indexbP[0] - 1] + indexbP # find index of X of base Point basePoint = Coordinate(listCoordinates[indexbP[0]], listCoordinates[indexbP[1]]) # object, consist of x and y width = max(listCoordinates[0::2]) - basePoint.x # calculate width of layout height = basePoint.y - min(listCoordinates[1::2]) # calculate height of layout return [basePoint, width, height] def _read(self): initialLayout = dict() tempBoundaries = list() tempObstacles = list() #iteration will consider only polyline type. Other objects will be ignored for obj in self.acad.iter_objects("Polyline"): try: if obj.layer == "Границы Цеха": tempBoundaries.extend(list(obj.coordinates)) #use extend because will be 1 list elif obj.layer == "Препятствия": tempObstacles.append(list(obj.coordinates)) #use append because can be several lists except Exception: print(f"Exception: ошибка при итерации по файлу {self.path2dwg}") continue # At first, we find base point, width and height of initial Layout boundary = self._getBPoint_W_H(tempBoundaries) self.data["Ширина Размещения"][0] = boundary[1] # обновляем значение ширины размещения после парсинга файла self.data["Высота Размещения"][0] = boundary[2] # обновляем значение высоты размещения после парсинга файла #at final, we find base point, width and height of all obstacles obstacles = list() for obstacle in tempObstacles: templist = self._getBPoint_W_H(obstacle) local_base_point = Coordinate(abs(boundary[0].x - templist[0].x), abs(boundary[0].y - templist[0].y)) obstacles.append([local_base_point, templist[1], templist[2]]) self.data.update({"Obstacles" : obstacles}) """ Печать лок координат препятствий, их ширины и высоты for i, o in enumerate(obstacles): print(f"лок коорд {i} фигуры", o[0].x, o[0].y) print(f"Ширина {i} фигуры", o[1]) print(f"Высота {i} фигуры", o[2]) """ def get(self): return self.data
class p2cad: def __init__(self): self.lst=[] self.ls_ar=[] # 把@数据存入ls_ar中 self.ls_inx=[] # 把@索引存入ls_inx中 self.spx = 100 # area startx self.spy = 2000 #area starty self.rw = 300 #area width self.rh = 400 #area height self.lst_p4 = [] #point4 x,y value self.fh=3 # font height self.m=0 # how many guizi in lst self.acad = Autocad(create_if_not_exists=True) txtsytle=self.acad.ActiveDocument.TextStyles.Add('HIT_TxtStyle') self.acad.ActiveDocument.ActiveTextStyle=self.acad.ActiveDocument.TextStyles.Item('Standard') self.acad.ActiveDocument.ActiveTextStyle.SetFont('楷体',False,False,1,0 or 0) self.TestB_Lock() self.txtlst=[] def TestB_Lock(self): return True def loadData(self,lst): self.lst=lst # print(self.lst) def addTxt(self,txt, posx, posy): txtObj = self.acad.model.AddText(txt, APoint(posx, posy), 3) self.txtlst.append(txtObj) def drawRec(self,px, py): p1 = APoint(px, py) p2 = APoint(p1.x + self.rw, p1.y) p3 = APoint(p2.x, p2.y + self.rh) p4 = APoint(p3.x - self.rw, p3.y) self.lst_p4.append(p4) l1 = self.acad.model.AddLine(p1, p2) l2 = self.acad.model.AddLine(p2, p3) l3 = self.acad.model.AddLine(p3, p4) l4 = self.acad.model.AddLine(p4, p1) def delTXT(self): for i in range(len(self.lst)): try: for obj in self.acad.iter_objects('Text'): obj.Delete() except: pass return 'del autocad TXT success' def pasreAndDrawToAutoCad(self): for f, value in enumerate(self.lst): if (value == '@'): self.ls_inx.append(f) # 判断lst中有几面柜子 self.ls_ar.append([]) #把每面柜子的数据存入ls_ar中 self.m=len(self.ls_inx) # total guizi # print('m',self.m) if(self.m>0): # 根据m面柜子的数量来判断画几行几列的框 # ############################################################## if (self.m % 10 > 0): lie = int(self.m / 10) + 1 else: lie = int(self.m / 10) for d in range(lie): for l in range(1, 11): self.drawRec(self.spx + self.rw * l + 30 * (l - 1), self.spy - self.rh * d - 30 * d) # ############################################################## # 把每面柜子的元素切入到列表ls_ar中 for i, v in enumerate(self.ls_inx): if (i == 0): self.ls_ar[0].append(self.lst[0:self.ls_inx[0]]) else: self.ls_ar[i].append(self.lst[(self.ls_inx[i - 1] + 1):(self.ls_inx[i - 1 + 1])]) # 把文字添加到方框中 for m in range(self.m): px = self.lst_p4[m].x py = self.lst_p4[m].y for u in range(len(self.ls_ar[m][0])): self.addTxt(str(self.ls_ar[m][0][u]), px + 10, py - 10 - 3 * u - 10 * u) # print(len(self.txtlst), 'txtlst') self.ls_ar.clear() self.ls_inx.clear() return 'success to draw dwg' else: return 'faild to draw dwg' ######################################################################################################## # if __name__ == '__main__': # lst = ['ggd1', 'list', 'lst2', 'lst3', '@', 'lst4', '@', 'lst6', '@', 'lst6', '@', 'ggd1', 'list', 'lst2', 'lst3', # '@', 'lst6', '@', 'lst6', '@', 'lst6', '@', 'lst6', '@', 'lst6', '@', 'lst6', '@', 'lst6', '@'] # # aa=p2cad() # aa.loadData(lst) # aa.pasreAndDrawToAutoCad()
from pyautocad import Autocad acad = Autocad(create_if_not_exists=True) # for obj in acad.iter_objects("Block"): # # 以下获取块的属性信息 # # 如果想获取某一特定块的属性信息可以用ObjectID识别特定块 # print(obj.ObjectName) # print(obj.InsertionPoint) # print(obj.Name) # for obj in acad.iter_objects("Line"): # print(obj.StartPoint) # print(obj.EndPoint) # print(obj.Layer) # print(obj.Length) # print(obj.Linetype) # print(obj.Lineweight) # print(obj.ObjectName) # print(obj.Visible) # print("----------------------") for obj in acad.iter_objects("Text"): print(obj.TextString) print(obj.Height) print(obj.InsertionPoint) print("----------------------")
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyautocad import Autocad, APoint acad = Autocad() acad.prompt("Hello, Autocad from Python\n") print acad.doc.Name p1 = APoint(0, 0) p2 = APoint(50, 25) for i in range(5): text = acad.model.AddText('Hi %s!' % i, p1, 2.5) acad.model.AddLine(p1, p2) acad.model.AddCircle(p1, 10) p1.y += 10 dp = APoint(10, 0) for text in acad.iter_objects('Text'): print('text: %s at: %s' % (text.TextString, text.InsertionPoint)) text.InsertionPoint = APoint(text.InsertionPoint) + dp for obj in acad.iter_objects(['Circle', 'Line']): print(obj.ObjectName)
# -*- coding: utf-8 -*- from pyautocad import Autocad, APoint acad = Autocad(create_if_not_exists=True) acad.prompt("Hello, Autocad from Python\n") print acad.doc.Name p1 = APoint(0, 0) p2 = APoint(50, 25) for i in range(5): text = acad.model.AddText(u'Hi %s!' % i, p1, 2.5) acad.model.AddLine(p1, p2) acad.model.AddCircle(p1, 10) p1.y += 10 for obj in acad.iter_objects(): print obj.ObjectName for text in acad.iter_objects('Text'): print text.TextString, text.InsertionPoint for obj in acad.iter_objects(['Text', 'Line']): print obj.ObjectName def text_contains_3(text_obj): return '3' in text_obj.TextString text = acad.find_one('Text', predicate=text_contains_3) print text.TextString from pyautocad import ACAD
APoint(0, 0).distance_to(APoint(50, 25)) # pyautocad.types.distance(p1, p2) distance(APoint(0, 0), APoint(50, 25)) ''' tuple(APoint(1, 1, 1)) -> (1.0, 1.0, 1.0) list(APoint(1, 1, 1)) -> [1.0, 1.0, 1.0] ''' ''' 文字 AcDbText ''' ''' AcDbArc_create 创建''' # AddText Method (ActiveX) # RetVal = object.AddText(TextString, InsertionPoint, Height) for _var in range(10): acad.model.AddText(_var, APoint(10 * _var, 10 * _var), 2.5) ''' AcDbArc_modify 修改''' for _var in acad.iter_objects('AcDbText'): # x = _var.InsertionPoint[0], y = _var.InsertionPoint[1] if _var.InsertionPoint[0] > 10 and _var.InsertionPoint[1] < 50: _var.TextString = 'Selected' ''' AcDbArc_delete 删除 ''' text_count = [] for _var in acad.iter_objects('AcDbText'): # x = _var.InsertionPoint[0], y = _var.InsertionPoint[1] if _var.InsertionPoint[0] > 10 and _var.InsertionPoint[1] < 50: text_count.append(_var) for _var in text_count: _var.Delete() ''' 多行文字 AcDbMText ''' # AddMText Method (ActiveX) # RetVal = object.AddMText(InsertionPoint, Width, Text) acad.model.AddMText(APoint(10, 10, 0), 25, '1111')
# -*- coding: UTF-8 -*- from pyautocad import Autocad, APoint # 这个true表示没有文件则打开一个,CAD有弹窗时会打开或者创建失败 acad = Autocad(create_if_not_exists=True) acad.prompt("Hello, Autocad from Python\n") print(acad.doc.Name) for text in acad.iter_objects('Text'): if text.TextString.find("YT4") >= 0: print('text: %s at: %s' % (text.TextString, text.InsertionPoint)) #text.InsertionPoint = APoint(text.InsertionPoint) + dp
class ApiTestCase(unittest.TestCase): def setUp(self): self.acad = Autocad(True) self.doc = self.acad.app.Documents.Add() print 'Current', self.doc.Name def tearDown(self): self.doc.Close(False) pass def test_points_arguments(self): model = self.acad.model p1 = APoint(0, 0, 0) for i in range(10): model.AddCircle(p1 * i, i + 1) p1 += i for circle in self.acad.iter_objects('circle'): cp = APoint(circle.Center) model.AddCircle(-cp, circle.Radius) def test_types(self): model = self.acad.model p1 = APoint(0, 0, 0) p2 = APoint(10, 10, 0) p3 = tuple(p+10 for p in p2) model.AddLine(p1, p2) model.AddLine(p2, APoint(p3)) lines = list(self.acad.iter_objects()) self.assertEqual(len(lines), 2) self.assertEqual(lines[0].StartPoint, p1) self.assertEqual(lines[0].EndPoint, p2) self.assertEqual(lines[1].StartPoint, p2) self.assertEqual(lines[1].EndPoint, p3) with self.assertRaises(COMError): model.AddLine(aDouble(0, 0), APoint(0, 0, 0)) def test_text(self): model = self.acad.model text1 = u'Русский текст' text2 = u'With paragraph \PYes' t1 = model.AddText(text1, APoint(0, 0, 0), 10) t2 = model.AddText(text2, APoint(10, 10, 0), 10) self.assertEqual(type(t1.TextString), unicode) self.assertEqual(t1.TextString, text1) self.assertEqual(t2.InsertionPoint, (10, 10, 0)) self.assertNotEqual(t2.InsertionPoint, (10, 10, 1)) def test_multitext(self): model = self.acad.model text1 = 'Line1\nLine2\nLine3\\' text2 = 'Line1\\PLine2\\PLine3\\P' t1 = model.AddMText(APoint(0,0,0), 10, text1) t2 = model.AddMText(APoint(10,10,0), 10, text2) self.assertEqual(t1.TextString, text1) self.assertEqual(t2.TextString, text2) def test_iter_objects(self): model = self.acad.model p1 = APoint(0, 0, 0) p2 = APoint(10, 10, 0) n_lines = 10 n_texts = 15 for i in range(n_lines): model.AddLine(p1, p2) for i in range(n_texts): model.AddMText(p2, 10, u'Dummy') lines_count = len(list(self.acad.iter_objects('Line'))) texts_count = len(list(self.acad.iter_objects('MText'))) all_count = len(list(self.acad.iter_objects(['MText', 'Line']))) self.assertEqual(lines_count, n_lines) self.assertEqual(texts_count, n_texts) self.assertEqual(all_count, n_lines + n_texts) def test_find_objects(self): p1 = APoint(0, 0) model = self.acad.model for i in range(5): text = model.AddText(u'test %s' % i, p1, 2.5) def text_contains_3(text_obj): return '3' in text_obj.TextString text = self.acad.find_one('Text', predicate=text_contains_3) self.assertEqual(text.TextString, 'test 3')
from pyautocad import Autocad, APoint import math acad = Autocad() acad.prompt("Hello, Autocad from Python\n") print(acad.doc.Name) p1 = APoint(0, 0) p2 = APoint(50, 25) for i in range(5): text = acad.model.AddText('Hi %s!' % i, p1, 2.5) acad.model.AddLine(p1, p2) acad.model.AddCircle(p1, 10) p1.y += 10 dp = APoint(10, 0) for text in acad.iter_objects('Text'): print('text: %s at: %s' % (text.TextString, text.InsertionPoint)) text.InsertionPoint = APoint(text.InsertionPoint) + dp for obj in acad.iter_objects(['Circle', 'Line']): print(obj.ObjectName)
from pyautocad import Autocad, APoint acad = Autocad(create_if_not_exists=True, visible=False) # 打开文件 filepath = r'C:\Users\Administrator\Desktop\dwgFiles\Circle.dwg' filename = filepath.split('\\')[-1] acad.Application.Documents.Open(filepath) # 设定文件为当前 acad.Application.Documents(filename).Activate() # 遍历文件中的对象 for obj in acad.iter_objects(): print(obj.ObjectName) if obj.ObjectName == 'AcDbCircle': desc = u"Shape:Circle\n" desc += u"Center:(" + str(obj.Center[0]) + u"," + str( obj.Center[1]) + u")\n" desc += u"Raidius:" + str(obj.Radius) + u"\n" desc += u"Diameter:" + str(obj.Diameter) + u"\n" desc += u"Area:" + str(obj.Area) + u"\n" desc += u"Circumference:" + str(obj.Circumference) px = obj.Center[0] + 1.1 * obj.Radius py = obj.Center[1] + 1.1 * obj.Radius desc_text = acad.model.addMText(APoint(px, py), obj.Radius, desc) h = obj.Radius / 7 desc_text.Height = h desc_text.Update() elif obj.ObjectName == 'AcDbText': print(obj.TextString)
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyautocad import Autocad, APoint from pyautocad.contrib import Table acad = Autocad() p1 = APoint(0, 0) for i in range(5): obj = acad.model.AddText(u'Hi %s!' % i, p1, 2.5) p1.y += 10 table = Table() for obj in acad.iter_objects('Text'): x, y, z = obj.InsertionPoint table.writerow([obj.TextString, x, y, z]) table.save('data.xls', 'xls') data = Table.data_from_file('data.xls')
class parseDWG: def __init__(self): self.path2dwg = "" self.data = {} def execute(self, data): self.data = data self.acad = Autocad( create_if_not_exists=True) # so far app is not open self.path2dwg = self.data[ "Строительная подоснова"] # refer to the key to the field where the link to this file if self.path2dwg == "": return "next" #если не указан путь до файла, то перейти к следующему объекту # TODO create windows attention about that in that time autocad will be opened self.acad.Application.Documents.open(self.path2dwg) self._read() self.acad.Application.Documents.close( ) # close previous file in autocad return "next" #returns coordinate of base point, width and height of each figure on the list def _getBPoint_W_H(self, listCoordinates): maxindexes = [ i * 2 + 1 for i, j in enumerate(listCoordinates[1::2]) if j == max(listCoordinates[1::2]) ] # возвращает индексы максимальных элементов по Y координате ( поэтому я указал отсчет со 2 элемента) minindexes = [ i * 2 for i, j in enumerate(listCoordinates[0::2]) if j == min(listCoordinates[0::2]) ] #теперь находим все минимальные indexbP = [i for i in maxindexes if (i - 1) in minindexes] # find index of Y of base Point indexbP = [indexbP[0] - 1] + indexbP # find index of X of base Point basePoint = Coordinate( listCoordinates[indexbP[0]], listCoordinates[indexbP[1]]) # object, consist of x and y width = max( listCoordinates[0::2]) - basePoint.x # calculate width of layout height = basePoint.y - min( listCoordinates[1::2]) # calculate height of layout return [basePoint, width, height] def _read(self): initialLayout = dict() tempBoundaries = list() tempObstacles = list() #iteration will consider only polyline type. Other objects will be ignored for obj in self.acad.iter_objects("Polyline"): try: if obj.layer == "Границы Цеха": tempBoundaries.extend(list( obj.coordinates)) #use extend because will be 1 list elif obj.layer == "Препятствия": tempObstacles.append( list(obj.coordinates )) #use append because can be several lists except Exception: print( f"Exception: ошибка при итерации по файлу {self.path2dwg}") continue # At first, we find base point, width and height of initial Layout boundary = self._getBPoint_W_H(tempBoundaries) self.data["Ширина Размещения"][0] = boundary[ 1] # обновляем значение ширины размещения после парсинга файла self.data["Высота Размещения"][0] = boundary[ 2] # обновляем значение высоты размещения после парсинга файла #at final, we find base point, width and height of all obstacles obstacles = list() for obstacle in tempObstacles: templist = self._getBPoint_W_H(obstacle) local_base_point = Coordinate(abs(boundary[0].x - templist[0].x), abs(boundary[0].y - templist[0].y)) obstacles.append([local_base_point, templist[1], templist[2]]) self.data.update({"Obstacles": obstacles}) """ Печать лок координат препятствий, их ширины и высоты for i, o in enumerate(obstacles): print(f"лок коорд {i} фигуры", o[0].x, o[0].y) print(f"Ширина {i} фигуры", o[1]) print(f"Высота {i} фигуры", o[2]) """ def get(self): return self.data
import json acad = Autocad() # db_circle = [] # n = 0 # for obj in acad.iter_objects('Circle'): # file = open('obj_cirlces.json', 'w') # db_circle.append({'Number': n, 'Centre': obj.Center, 'Layer': obj.Layer, 'ObjectName': obj.ObjectName}) # n += 1 # json.dump(db_circle, file, indent=1) # file.close() db_lines = [] m = 0 for obj in acad.iter_objects('Line'): file = open('obj_lines.json', 'w') db_lines.append({ 'Number': m, 'ObjectName': obj.ObjectName, 'ObjectID': obj.ObjectID, 'Handle': obj.Handle, 'Length': obj.Length, 'Layer': obj.Layer }) m += 1 json.dump(db_lines, file, indent=1) file.close() pp = APoint(2210581.291, 488153.2095) acad.model.AddTable(pp, len(db_lines) + 4, 10, 8, 45)
# for i in range(5): # text = acad.model.AddText('Hi %s!' % i, p1, 2.5) # acad.model.AddLine(p1, p2) # acad.model.AddCircle(p1, 10) # p1.y += 10 # # dp = APoint(10, 0) # for text in acad.iter_objects('Text'): # print(text.InsertionPoint) # text.InsertionPoint = APoint(text.InsertionPoint) + dp # # for i in range(4): # text = acad.model.AddMText('Hi %s!' % i, p1, 2.5) # points = [] for obj in acad.iter_objects('Circle'): if obj.Layer == 'СИП С1-85 пром': points.append(obj.Center) print(points) # print(obj.Layer) # points.append(obj.Name) # print(points) # a = 0 # for i in range(len(points)): # if distance(points[a], (points[a+1]) < 60: # print(distance(points[a], (points[a+1]) # try: # acad.model.AddLine(APoint(points[a]), APoint(points[a+1])) # a += 1