def create_dxf_drawing(): dwg = ezdxf.new(DXF_VERSION) dwg.layers.new(name=LAYER_NAME, dxfattribs=DXF_ATTRIBS) return dwg
def main(): source_dwg = ezdxf.readfile('CustomBlocks.dxf') target_dwg = ezdxf.new(source_dwg.dxfversion) importer = ezdxf.Importer(source_dwg, target_dwg) importer.import_blocks(query='CustomBlock1') importer.import_modelspace_entities() target_dwg.saveas("CustomBlocks_Import.dxf")
def draw_layers_and_points_to_dxf(cls, layers, filename, folder_name): filepath = os.path.join(DXF_DEST_DIR, folder_name, filename) dwg = ezdxf.new('R2010') msp = dwg.modelspace() cls.add_layer_to_drawing(dwg, msp, 'outline', layers['outline']) for c in layers['cuts']: cls.add_layer_to_drawing(dwg, msp, 'cuts', c) dwg.saveas(filepath) logger.info("Drawing Divider to file(%s)" % (filepath))
def joinDXF(boxid): target_drawing = ezdxf.new(dxfversion='AC1024') print target_drawing.dxfversion target_filename = outdir + "/boxmaze_" + str(boxid) + ".dxf" FILES = [ "pieces.dxf", "maze.dxf", "boxmaze.dxf", "id_numbers.dxf" ] for file in FILES: filename = dxfdir + file print "processing " + filename dxf = ezdxf.readfile(filename) importer = ezdxf.Importer(dxf, target_drawing) importer.import_all(table_conflict='discard', block_conflict='discard') target_drawing.saveas(target_filename)
def save_dxf(self,basename,separate_files=False,directory = None): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir if directory is None: directory = popupcad.exportdir if not separate_files: filename = os.path.normpath(os.path.join(directory,basename+'.dxf')) dwg = ezdxf.new('AC1015') msp = dwg.modelspace() for ii,layer in enumerate(self.layerdef.layers): layername = '{:03.0f}_'.format(ii)+layer.name if separate_files: filename = os.path.normpath(os.path.join(directory,basename+'_'+layername+'.dxf')) dwg = ezdxf.new('AC1015') msp = dwg.modelspace() dwg.layers.create(name=layername) for item in self.geoms[layer]: if not item.is_construction(): item.output_dxf(msp,layername) if separate_files: dwg.saveas(filename) if not separate_files: dwg.saveas(filename)
def create_solid_polyline_hatch(): dwg = ezdxf.new("Ac1024") # create a new DXF drawing (AutoCAD 2010) msp = dwg.modelspace() # we are working in model space hatch = msp.add_hatch(color=2) # by default a SOLID fill with hatch.edit_boundary() as editor: # get boundary editor as context object editor.add_polyline_path([(0, 0), (0, 3), (3, 6), (6, 6), (6, 3), (3, 0)]) dwg.saveas("hatch_solid_polyline.dxf") # save DXF drawing
def make_drawing(version): dwg = ezdxf.new(version) points2d = [(0,0), (1,0), (1,1), (0,1), (0,0), (1,1), (.5, 1.5), (0, 1), (1,0)] add_polyline2d_entities(dwg.modelspace(), points2d) points3d = [(3, 3, 0), (6, 3, 1), (6, 6, 2), (3, 6, 3), (3, 3, 4)] add_polyline3d_entities(dwg.modelspace(), points3d) dwg.saveas('polylines_%s.dxf' % version)
def using_hatch_with_spline_edge(): dwg = ezdxf.new("Ac1024") # create a new DXF drawing (AutoCAD 2010) msp = dwg.modelspace() # we are working in model space # draw outline vertices = [(8, 0, 0), (10, 2, 0), (6, 6, 0), (8, 8, 0)] msp.add_line((8, 8), (0, 8)) msp.add_line((0, 8), (0, 0)) msp.add_line((0, 0), (8, 0)) msp.add_spline(vertices) # next create DXF hatch entities hatch = msp.add_hatch(color=3) with hatch.edit_boundary() as editor: # get boundary editor as context object path = editor.add_edge_path() # create a new edge path path.add_line((8, 8), (0, 8)) path.add_line((0, 8), (0, 0)) path.add_line((0, 0), (8, 0)) spline = path.add_spline(vertices) # This control points are taken from a hatch created by AutoCAD, because this values are necessary otherwise # AutoCAD crashes. Sadly AutoCAD doesn't calculate this values by itself, like it does for the SPLINE entity cpoints = [(8.0, 0.0), (9.0, 0.66), (12.0, 2.67), (4.0, 5.33), (7.0, 7.33), (8.0, 8.0)] spline.control_points = cpoints # I found this knot function on the internet - but the generated values do not match the values calculated by # AutoCAD for the SPLINE entity spline.knot_values = knot_values_by_control_points(cpoints, spline.degree) dwg.saveas("hatch_with_spline_edge.dxf") # save DXF drawing
def make_dxf2(xyrra_list): """turn an xyrra_list (xcenter, ycenter, radius_x, radius_y, angle of rotation) into a dxf file. Should be identical to make_dxf(). Seems to run 3X faster. Note: When I tried this, it looked good except for 2 random polylines near the center that I had to delete by hand. Weird! Always check your files.""" directory_now = os.path.dirname(os.path.realpath(__file__)) dwg = ezdxf.new('AC1015') msp = dwg.modelspace() points = [(0, 0), (3, 0), (6, 3), (6, 6)] msp.add_lwpolyline(points) for i in range(xyrra_list.shape[0]): if i % 10000 == 0: print(xyrra_list.shape[0] - i, 'ellipses remaining in dxf creation...', flush=True) x,y,rx,ry,a = xyrra_list[i,:] if rx == ry: msp.add_circle((x/um,y/um), rx / um) else: ellipse_pts = grating.ellipse_pts(x/um,y/um, rx/um, ry/um, a, num_points=16) # repeat first point twice ellipse_pts = np.vstack((ellipse_pts, ellipse_pts[0,:])) msp.add_lwpolyline(ellipse_pts) print('saving dxf...', flush=True) dwg.saveas(os.path.join(directory_now, "test2.dxf"))
def make_drawing(version): dwg = ezdxf.new(version) modelspace = dwg.modelspace() anonymous_block = dwg.blocks.new_anonymous_block() points2d = [(0,0), (1,0), (1,1), (0,1), (0,0), (1,1), (.5, 1.5), (0, 1), (1,0)] anonymous_block.add_polyline2d(points2d) modelspace.add_blockref(anonymous_block.name, (0, 0)) dwg.saveas('anonymous_blocks_%s.dxf' % version)
def test_delete_all_entities_DXF12(self): dwg = ezdxf.new('AC1009') m = dwg.modelspace() for _ in range(5): m.add_line((0, 0), (1, 1)) self.assertEqual(5, len(dwg.entities)) dwg.entities.delete_all_entities() self.assertEqual(0, len(dwg.entities))
def make_test_drawing(version): dwg = ezdxf.new(version) modelspace = dwg.modelspace() modelspace.add_line((0, 0), (10, 0), {'layer': 'lay_line'}) modelspace.add_text("TEST", dxfattribs={'layer': 'lay_line'}) modelspace.add_polyline2d([(0, 0), (3, 1), (7, 4), (10, 0)], {'layer': 'lay_polyline'}) # just 3 entities: LINE, TEXT, POLYLINE - VERTEX & SEQEND now linked to the POLYLINE entity, and do not appear # in any entity space return dwg
def custom_header_vars(): dwg = ezdxf.new('AC1015') msp = dwg.modelspace() points = [(0, 0), (3, 0), (6, 3), (6, 6)] msp.add_polyline2d(points) dwg.header.custom_vars.append("Name", "Manfred Moitzi") dwg.header.custom_vars.append("Adresse", "8020 Graz") dwg.saveas("custom_header_vars.dxf")
def _init_drawing(self): """Create a drawing, set some global information and add the layers we need. """ drawing = ezdxf.new(dxfversion=self.dxfversion) modelspace = drawing.modelspace() drawing.header['$EXTMIN'] = (0, 0, 0) drawing.header['$EXTMAX'] = (self.width, self.height, 0) self.drawing = drawing self.modelspace = modelspace
def make_id( id ): global modelspace drawing = ezdxf.new(dxfversion='AC1024') modelspace = drawing.modelspace() print "using id %d" % id id_str = str(id) for i in range( len( id_str )): print id_str[i] x = i * char_width + char_spacing * i create_num( x, 0, int(id_str[i]) ) drawing.saveas(dxfdir+'id_numbers.dxf')
def create_group(): dwg = ezdxf.new('Ac1015') msp = dwg.modelspace() # create a new unnamed group, in reality they have a name like '*Annnn' and group names have to be unique group = dwg.groups.add() # group management is implemented as context manager, returning a standard Python list with group.edit_data() as g: # the group itself is not an entity space, DXF entities has to be placed in model space, paper space # or in a block g.append(msp.add_line((0, 0), (3, 0))) g.append(msp.add_circle((0, 0), radius=2)) dwg.saveas('group.dxf')
def save_dxf(self,filename): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir dwg = ezdxf.new('AC1015') msp = dwg.modelspace() for item in self.operationgeometry: if not item.is_construction(): item.output_dxf(msp) dwg.saveas(filename)
def main(): dwg = ezdxf.new('AC1009') # block creation block = dwg.blocks.new('TEST') block.add_line((-1, -1), (+1, +1)) block.add_line((-1, +1), (+1, -1)) # block usage ms = dwg.modelspace() ms.add_blockref('TEST', (5, 5)) dwg.saveas('using_blocks.dxf')
def dxf_merge(files, colors = range(0, 256), nolayer = False): 'merge DXF file and convert continuous line to polyline.' # DXF file dwg = ezdxf.new('AC1015') msp = dwg.modelspace() # layer vars layer_num = 1 layer_name = 'layer0' layer_names = [] layer_colors = iter(colors) layer_color = next(layer_colors) # for each files for file in files: # layer name if nolayers == False: layer_name = os.path.basename(file) n = layer_name i = 1 while n in layer_names: n = layer_name + '_' + str(i) i += 1 layer_names.append(n) layer_name = n # create layer if layer_num < 2 or nolayers == False: dwg.layers.create( name = layer_name, dxfattribs = {'color': layer_color}) # parse file polylines = dxf_parse(file) if len(polylines): for polyline in polylines: msp.add_lwpolyline(polyline, dxfattribs={'layer': layer_name}) # next layer color layer_color = next(layer_colors, False) if layer_color == False: layer_colors = iter(colors) layer_color = next(layer_colors) # increment layer num layer_num += 1 #return the dwg object return dwg
def save_dxf(self,filename,update_filename = True): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir dwg = ezdxf.new('AC1015') msp = dwg.modelspace() for item in self.operationgeometry: if not item.is_construction(): item.output_dxf(msp) dwg.saveas(filename) newfile = os.path.splitext(filename)[0]+'.sketch' self.updatefilename(newfile)
def save_dxf(self,filename): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir dwg = ezdxf.new('AC1015') msp = dwg.modelspace() for ii,layer in enumerate(self.layerdef.layers): layername = '{:03.0f}_'.format(ii)+layer.name dwg.layers.create(name=layername) for item in self.geoms[layer]: if not item.is_construction(): item.output_dxf(msp,layername) dwg.saveas(filename)
def create_source_drawing(version): dwg = ezdxf.new(version) dwg.layers.create('Test', dxfattribs={'color': 17}) dwg.layers.create('TestConflict', dxfattribs={'color': 18}) msp = dwg.modelspace() msp.add_line((0, 0), (10, 0)) msp.add_circle((0, 0), radius=5) msp.add_blockref("TestBlock", insert=(0, 0)) msp.add_blockref("ConflictBlock", insert=(0, 0)) build_block(dwg, "TestBlock") build_block(dwg, "ConflictBlock") block = build_block(dwg, "RefToConflictBlock") block.add_blockref('ConflictBlock', insert=(0,0)) #save_source_dwg(dwg, 'ImportSource-' + version + '.dxf') return dwg
def using_hatch_style_with_edge_path(): def add_edge_path(path_editor, vertices): path = path_editor.add_edge_path() # create a new edge path first_point = next(vertices) # store first point for closing path last_point = first_point for next_point in vertices: path.add_line(last_point, next_point) # add lines to edge path last_point = next_point path.add_line(last_point, first_point) # close path def place_square_1(hatch, x, y): def shift(point): return x+point[0], y+point[1] with hatch.edit_boundary() as editor: # get boundary editor as context object add_edge_path(editor, map(shift, [(0, 0), (0, 8), (8, 8), (0, 8)])) # 1. path add_edge_path(editor, map(shift, [(2, 2), (7, 2), (7, 7), (2, 7)])) # 2. path add_edge_path(editor, map(shift, [(4, 4), (6, 4), (6, 6), (4, 6)])) # 3. path def place_square_2(hatch, x, y): def shift(point): return x+point[0], y+point[1] with hatch.edit_boundary() as editor: # get boundary editor as context object add_edge_path(editor, map(shift, [(0, 0), (0, 8), (8, 8), (0, 8)])) # 1. path add_edge_path(editor, map(shift, [(3, 1), (7, 1), (7, 5), (3, 5)])) # 2. path add_edge_path(editor, map(shift, [(1, 3), (5, 3), (5, 7), (1, 7)])) # 3. path dwg = ezdxf.new("Ac1024") # create a new DXF drawing (AutoCAD 2010) msp = dwg.modelspace() # we are working in model space # first create DXF hatch entities hatch_style_0 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 0}) hatch_style_1 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 1}) hatch_style_2 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 2}) # then insert path elements to define the hatch boundaries place_square_1(hatch_style_0, 0, 0) place_square_1(hatch_style_1, 10, 0) place_square_1(hatch_style_2, 20, 0) # first create DXF hatch entities hatch_style_0b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 0}) hatch_style_1b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 1}) hatch_style_2b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 2}) # then insert path elements to define the hatch boundaries place_square_2(hatch_style_0b, 0, 10) place_square_2(hatch_style_1b, 10, 10) place_square_2(hatch_style_2b, 20, 10) dwg.saveas("hatch_styles_examples_with_edge_path.dxf") # save DXF drawing
def draw_Models(aModels, cad_ver="AC1015", save_name="new.dxf"): '''draw Models, cad_ver can be \"2010\" or \"AC1024\"''' typeTest([Models, str, str], aModels, cad_ver, save_name) # create dxf obj and modelspace if cad_ver in ver.const.keys(): cad_ver = ver.const[cad_ver] dxf = ezdxf.new(cad_ver) msp = dxf.modelspace() # draw models in Models for m in aModels: m.draw(msp) # save as dxf file dxf.saveas(save_name)
def create_dwg(filename): def add_justify_text(content, p1, p2, align): msp.add_text(content).set_pos(p1, p2, align) msp.add_line(p1, p2) def add_grid(pos, width, height): attribs = {'height': 0.2, 'color': 3} x, y = pos dx = width / 2 dy = height / 2 msp.add_line((x, y), (x, y+height)) msp.add_line((x+dx, y), (x+dx, y+height)) msp.add_line((x+width, y), (x+width, y+height)) msp.add_line((x, y-1), (x+width, y-1)) msp.add_text('BASELINE ADJUSTMENTS', dxfattribs=attribs).set_pos((x, y-1.5)) msp.add_text('LEFT', dxfattribs=attribs).set_pos((x, y-1), align='LEFT') msp.add_text('CENTER', dxfattribs=attribs).set_pos((x+dx, y-1), align='CENTER') msp.add_text('RIGHT', dxfattribs=attribs).set_pos((x+width, y-1), align='RIGHT') attribs['color'] = 2 msp.add_line((x, y), (x+width, y)) msp.add_text('BOTTOM_LEFT', dxfattribs=attribs).set_pos((x, y), align='BOTTOM_LEFT') msp.add_text('BOTTOM_CENTER', dxfattribs=attribs).set_pos((x+dx, y), align='BOTTOM_CENTER') msp.add_text('BOTTOM_RIGHT', dxfattribs=attribs).set_pos((x+width, y), align='BOTTOM_RIGHT') y += dy msp.add_line((x, y), (x+width, y)) msp.add_text('MIDDLE_LEFT', dxfattribs=attribs).set_pos((x, y), align='MIDDLE_LEFT') msp.add_text('MIDDLE_CENTER', dxfattribs=attribs).set_pos((x+dx, y), align='MIDDLE_CENTER') msp.add_text('MIDDLE_RIGHT', dxfattribs=attribs).set_pos((x+width, y), align='MIDDLE_RIGHT') y += dy msp.add_line((x, y), (x+width, y)) msp.add_text('TOP_LEFT', dxfattribs=attribs).set_pos((x, y), align='TOP_LEFT') msp.add_text('TOP_CENTER', dxfattribs=attribs).set_pos((x+dx, y), align='TOP_CENTER') msp.add_text('TOP_RIGHT', dxfattribs=attribs).set_pos((x+width, y), align='TOP_RIGHT') dwg = ezdxf.new(dxfversion='AC1018') # AutoCAD R2004 msp = dwg.modelspace() add_justify_text("ALIGNED-TEXT", (15,0), (35, 5), 'ALIGNED') add_justify_text("FITTED-TEXT", (15,10), (35, 5), 'FIT') add_grid((0, 0), width=10, height=10) dwg.saveas(filename)
def convert(svg_in, dxf_out, layer_to_style=None, debug_out=None): if debug_out is not None: debug = lambda *objects: print(*objects, file=debug_out) else: debug = _noop with stdout_ignore(): svg = pysvg.parser.parse(svg_in) dwg = ezdxf.new('AC1015') create_layers(dwg, layer_to_style) msp = dwg.modelspace() transform_ = transform.matrix(1, 0, 0, -1, 0, 0) context = ElementContext(transform_=transform_).element(svg) _append_subelements(svg, msp, debug, context) dwg.write(dxf_out)
def drawMaze( jstr,box ): global transX,transY,modelspace,drawColor,maze,xCells,yCells (xCells,yCells)=box.getDimensions() drawing = ezdxf.new(dxfversion='AC1024') modelspace = drawing.modelspace() #import the maze matrix = json.loads( jstr ) maze = [[Cell(x,y,matrix[x][y]) for y in range(yCells)] for x in range(xCells)] transX = 40 transY = 195 #190 drawColor = settings.CUTCOLOR drawDXFMaze() drawColor = settings.PATTERNCOLOR transX = 185 #180 transY = 300 #290 drawDXFMaze() drawing.saveas(dxfdir+'maze.dxf')
def run(self): global UsrAppId, TemCTNula #dxfPath=os.path.join(self.dirname,'test.dxf')#substituir por filedialog self.ImportDxf_Lib() noth=['',' ','.dxf'] if self.dlg.txtFile.text() in noth: proj = QgsProject.instance() #baseName=proj.readPath("./") prjfi = os.path.splitext(QgsProject.instance().fileName())[0]+'.dxf' self.dlg.txtFile.setText(prjfi) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: dxfPath=self.dlg.txtFile.text() Invalidos=['',' ',None,NULL] if dxfPath in Invalidos: aviso=self.tr(u'Operação cancelada!') iface.messageBar().pushMessage(ClassName, aviso, level=QgsMessageBar.INFO, duration=4) return dxf=self.dxf # Create a new drawing in the DXF format of AutoCAD 2010 drawing = dxf.new('ac1024') self.drawing=drawing drawing.header['$INSUNITS'] = 6 #set units to meters drawing.header['$AUNITS'] = 0 #set angle unit to decimal degrees drawing.header['$AUPREC'] = 6 #set angles precision drawing.appids.new(UsrAppId) #Create AppId entry to xdata self.criaRede() # Save the drawing. drawing.saveas(dxfPath) aviso=self.tr("Salvo em:") + dxfPath if TemCTNula: aviso=self.tr("Valores nulos foram substituidos por Zeros. ")+aviso iface.messageBar().pushMessage(ClassName, aviso, level=QgsMessageBar.WARNING, duration=4) else: iface.messageBar().pushMessage(ClassName, aviso, level=QgsMessageBar.INFO, duration=4)
def make_pieces( t ): global modelspace, thickness thickness = t print "using thickness %f" % thickness drawing = ezdxf.new(dxfversion='AC1024') modelspace = drawing.modelspace() #drawRef() drawHinge(205,40) drawHinge(230,40) drawCatch(60,40) spacing = 5 drawLidCatchSlot(0,0) # drawLowerLidCatchSlot(boxLength*0,0) for col in range(2): for row in range(4): if (row == 3 and col == 1): None elif (row == 0 and col == 0): drawHingeSlotLid((boxLength+spacing)*col,(boxWidth+spacing)*row) else : drawHingeSlot((boxLength+spacing)*col,(boxWidth+spacing)*row) drawing.saveas(dxfdir+'pieces.dxf')
def using_hatch_style(): def place_square_1(hatch, x, y): def shift(point): return x+point[0], y+point[1] with hatch.edit_boundary() as editor: # get boundary editor as context object editor.add_polyline_path(map(shift, [(0, 0), (0, 8), (8, 8), (0, 8)])) # 1. path editor.add_polyline_path(map(shift, [(2, 2), (7, 2), (7, 7), (2, 7)])) # 2. path editor.add_polyline_path(map(shift, [(4, 4), (6, 4), (6, 6), (4, 6)])) # 3. path def place_square_2(hatch, x, y): def shift(point): return x+point[0], y+point[1] with hatch.edit_boundary() as editor: # get boundary editor as context object editor.add_polyline_path(map(shift, [(0, 0), (0, 8), (8, 8), (0, 8)])) # 1. path editor.add_polyline_path(map(shift, [(3, 1), (7, 1), (7, 5), (3, 5)])) # 2. path editor.add_polyline_path(map(shift, [(1, 3), (5, 3), (5, 7), (1, 7)])) # 3. path dwg = ezdxf.new("Ac1024") # create a new DXF drawing (AutoCAD 2010) msp = dwg.modelspace() # we are working in model space # first create DXF hatch entities hatch_style_0 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 0}) hatch_style_1 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 1}) hatch_style_2 = msp.add_hatch(color=3, dxfattribs={'hatch_style': 2}) # then insert path elements to define the hatch boundaries place_square_1(hatch_style_0, 0, 0) place_square_1(hatch_style_1, 10, 0) place_square_1(hatch_style_2, 20, 0) # first create DXF hatch entities hatch_style_0b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 0}) hatch_style_1b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 1}) hatch_style_2b = msp.add_hatch(color=7, dxfattribs={'hatch_style': 2}) # then insert path elements to define the hatch boundaries place_square_2(hatch_style_0b, 0, 10) place_square_2(hatch_style_1b, 10, 10) place_square_2(hatch_style_2b, 20, 10) dwg.saveas("hatch_styles_examples.dxf") # save DXF drawing
def dwg(): return ezdxf.new('R2007')
def target(): doc = ezdxf.new() # for different handles for x in range(10): doc.entitydb.next_handle() return doc.modelspace()
def generate_dxf(filename, tags): lat2y = lambda lat: (180/pi * log(tan(pi/4+lat*(pi/180)/2))) doc = ezdxf.new('R2018') msp = doc.modelspace() xml = libxml2.parseFile(filename) context = xml.xpathNewContext() for tag in tags: layer_name = tag.upper() paths = context.xpathEval("/*/way[tag/@k = '%s']" %(tag)) doc.layers.new(name=layer_name) n = context.xpathEval("/*/node") lat = {} lon = {} for node in n: lat[node.prop('id')] = float(node.prop('lat')) lon[node.prop('id')] = float(node.prop('lon')) xmax = max(lon.items(), key=operator.itemgetter(1))[1] xmin = min(lon.items(), key=operator.itemgetter(1))[1] ymax = max(lat.items(), key=operator.itemgetter(1))[1] ymin = min(lat.items(), key=operator.itemgetter(1))[1] print("Rectangle: [%f, %f], [%f, %f]" % (xmin, xmax, ymin, ymax)) masterscale = 500/(xmax-xmin) baselong = xmin basey = lat2y(ymin) lat2coord = lambda lat: (lat2y(lat)-basey)*masterscale long2coord = lambda lon: (lon-baselong)*masterscale print("found %d nodes for %s, cached them" %(len(lat), layer_name)) print("found %d paths" %(len(paths))) for path in paths: # check if path has elevation information ele = path.xpathEval("tag[@k = 'ele']") if len(ele) == 0: elevation = 0.0 else: elevation = float(ele[0].prop('v')) # find all nodes in path nodes = path.xpathEval("nd") points = [] closed_path = False for node in nodes: if node.prop('ref') in lon and node.prop('ref') in lat: points.append( (long2coord(lon[node.prop('ref')]), lat2coord(lat[node.prop('ref')]), float(elevation)/15.0) ) else: print("Key %s not found in lat or long dict! Skipping...") polyline = msp.add_lwpolyline(points, dxfattribs={'layer': layer_name}) if nodes[-1].prop('ref') == nodes[0].prop('ref'): closed_path = True polyline.close() print("Writing %s path for layer %s with elevation=%dm, %d nodes" %("closed" if closed_path else "", layer_name, elevation, len(nodes))) print("Saving file...") doc.saveas(filename + ".dxf") print("Done.")
def doc(self): d = ezdxf.new() new_style = d.mline_styles.new('NewStyle1') new_style.elements.append(0.5) new_style.elements.append(0) return d
def new_dwg(): return ezdxf.new('AC1015')
# Copyright (c) 2018-2021 Manfred Moitzi # License: MIT License import ezdxf from ezdxf.math import Vec3, ConstructionArc, UCS doc = ezdxf.new("R2000") modelspace = doc.modelspace() # create a 2D arcs in xy-plane delta = 30 for count in range(12): modelspace.add_arc( center=(0, 0), radius=10 + count, start_angle=count * delta, end_angle=(count + 1) * delta, ) # create a 3D arc from 3 points in WCS start_point_wcs = Vec3(3, 0, 0) end_point_wcs = Vec3(0, 3, 0) def_point_wcs = Vec3(0, 0, 3) # create UCS ucs = UCS.from_x_axis_and_point_in_xy( origin=def_point_wcs, axis=start_point_wcs - def_point_wcs, point=end_point_wcs, ) start_point_ucs = ucs.from_wcs(start_point_wcs) end_point_ucs = ucs.from_wcs(end_point_wcs)
def doc(self): return ezdxf.new()
import ezdxf # 8 corner vertices p = [ (0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ] dwg = ezdxf.new('AC1015') # mesh requires the DXF 2000 or newer format msp = dwg.modelspace() mesh = msp.add_mesh() with mesh.edit_data() as mesh_data: mesh_data.add_face([p[0], p[1], p[2], p[3]]) mesh_data.add_face([p[4], p[5], p[6], p[7]]) mesh_data.add_face([p[0], p[1], p[5], p[4]]) mesh_data.add_face([p[1], p[2], p[6], p[5]]) mesh_data.add_face([p[3], p[2], p[6], p[7]]) mesh_data.add_face([p[0], p[3], p[7], p[4]]) mesh_data.optimize() dwg.saveas("cube_mesh_2.dxf")
import random import ezdxf from ezdxf.addons import r12writer from ezdxf.tools.standards import setup_dimstyle DIR = Path("~/Desktop/Outbox").expanduser() XSIZE, YSIZE = (100, 100) COUNT = 1000 POINTS = [(random.random() * XSIZE, random.random() * YSIZE) for _ in range(COUNT)] XREF = "points.dxf" # scale 1:1000; text size H = 2.5mm on paper; 1 drawing unit = 1m DIMSTYLE = "USR_M_1000_H25_M" with r12writer(str(DIR / XREF)) as r12: for point in POINTS: r12.add_point(point, layer="Points") doc = ezdxf.new("R2000", setup=True) doc.add_xref_def(filename=".\\" + XREF, name="points_xref") msp = doc.modelspace() msp.add_blockref(name="points_xref", insert=(0, 0)) setup_dimstyle(doc, fmt=DIMSTYLE, style=ezdxf.options.default_dimension_text_style) msp.add_aligned_dim(p1=(0, 0), p2=(0, 100), distance=5, dimstyle=DIMSTYLE) msp.add_aligned_dim(p1=(0, 100), p2=(100, 100), distance=5, dimstyle=DIMSTYLE) doc.set_modelspace_vport(height=YSIZE * 1.25, center=(XSIZE / 2, YSIZE / 2)) doc.saveas(DIR / "host.dxf")
import ezdxf import numpy doc = ezdxf.new(dxfversion='R2010') doc.header['$MEASUREMENT'] = 1 doc.header['$INSUNITS'] = 4 # mil # Create new table entries (layers, linetypes, text styles, ...). doc.layers.new('TEXTLAYER', dxfattribs={'color': 2}) doc.layers.new('STRCUT', dxfattribs={'color': 5}) doc.layers.new('REBAR', dxfattribs={'color': 1}) msp = doc.modelspace() #input_format column_data = [ { "mark": "C1", "width": "300", "height": "300", "rebar_options": { #4mainbar "main": { "size": 12 }, #extra_bar "vertical": { "number": 3, "size": 12 } #extra_bar
def dwg(): return ezdxf.new('AC1009')
def doc(): return ezdxf.new()
def doc(): d = ezdxf.new(setup=True) d.layers.new( 'Test', dxfattribs={ 'color': 5, # blue: 0000ff 'linetype': 'DOT', 'lineweight': 70, # 0.70 }) msp = d.modelspace() msp.add_line( (0, 0), (1, 0), dxfattribs={ 'color': 256, # by layer 'linetype': 'BYLAYER', 'lineweight': -1, # by layer 'layer': 'Test', }) msp.add_line( (0, 0), (1, 0), dxfattribs={ 'color': 1, # red: ff0000 'linetype': 'DASHED', 'lineweight': 50, # 0.50 'layer': 'Test', }) blk = d.blocks.new('MyBlock') blk.add_line( (0, 0), (1, 0), dxfattribs={ 'color': 0, # by block 'linetype': 'BYBLOCK', 'lineweight': -2, # by block 'layer': 'Test', }) blk.add_line( (0, 0), (1, 0), dxfattribs={ 'color': 1, # red: ff0000 'linetype': 'DASHED', 'lineweight': 50, # 0.50 'layer': 'Test', }) blk.add_line( (0, 0), (1, 0), dxfattribs={ 'color': 256, # by layer 'linetype': 'BYLAYER', 'lineweight': -1, # by layer 'layer': 'Test', }) msp.add_blockref( 'MyBlock', insert=(0, 0), dxfattribs={ 'color': 3, # green: 00ff00 'linetype': 'CENTER', 'lineweight': 13, # 0.13 }) return d
def test_create_new_geo_data_for_model_space(): dwg = ezdxf.new('R2010') msp = dwg.modelspace() assert msp.get_geodata() is None geodata = msp.new_geodata() assert geodata.dxftype() == 'GEODATA'
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import ezdxf doc = ezdxf.new() msp = doc.modelspace() width = 40 height = 4 for i in range(26): c = chr(ord("a") + i) msp.add_mtext(f"{c}: abc^{c}def", {"insert": (0, -i * height, 0)}) for i in range(26): c = chr(ord("A") + i) msp.add_mtext(f"{c}: abc^{c}def", {"insert": (width, -i * height, 0)}) for i, c in enumerate(["?", "@", "[", "]", "\\", "_", " "]): msp.add_mtext(f"{c}: abc^{c}def", {"insert": (2 * width, -i * height, 0)}) msp.add_mtext(f"^ : abc^^def", {"insert": (2 * width, -(i + 1) * height, 0)}) msp.add_mtext("^", {"insert": (2 * width, -(i + 2) * height, 0)}) doc.saveas("caret_encoding.dxf")
modelspace = dwg.modelspace() for x in range(10): for y in range(10): xcoord = x * 10 ycoord = y * 10 values = {'XPOS': "x = %d" % xcoord, 'YPOS': "y = %d" % ycoord} modelspace.add_auto_blockref('MARKER', (xcoord, ycoord), values) def set_active_viewport(dwg): try: active_viewport = dwg.viewports.get('*ACTIVE') except ValueError: active_viewport = dwg.viewports.new('*ACTIVE') # first try, the logic way - but wrong! # active_viewport.dxf.lower_left = (20, 20) # active_viewport.dxf.upper_right = (40, 30) # second try active_viewport.dxf.center_point = ( 40, 30) # center of viewport, this parameter works active_viewport.dxf.height = 15 # height of viewport, this parameter works active_viewport.dxf.aspect_ratio = 1.5 # aspect ratio of viewport (x/y) if __name__ == '__main__': dwg = ezdxf.new('AC1015') draw_raster(dwg) set_active_viewport(dwg) dwg.saveas(FILENAME) print("drawing '%s' created.\n" % FILENAME)
def msp(self): return ezdxf.new().modelspace()
def worker(): # read json + reply print 'hi.....inside Python' data = request.get_json(force=True) result = '' print type(data) result = json.dumps(data) #print result result = json.loads(result) print type(result) #check whether the feature data is a linestring or point type numFeats = len(result['features']) if (numFeats > 0): geometryType = result['features'][0]['geometry']['type'] print geometryType, type(geometryType) #if type is linestring, run the linestring code; if (str(geometryType) == 'LineString'): print "hello" AttribInfo = result['features'][0]['properties'] Attribs = AttribInfo.keys() #print AttribInfo #line information/coordinates only, copied from writeLinestring.py with r12writer("write_Lines.dxf") as dxf: #where is this file being written? for i in range(numFeats): a_linefeature = result['features'][i]['geometry'][ 'coordinates'] dxf.add_polyline(a_linefeature) strDict = result['features'][i]['properties'] strDict = json.dumps(strDict) strDict = strDict.encode('ascii', 'replace') dxf.add_text(strDict[1:-1], insert=(a_linefeature[0][0], a_linefeature[0][1])) #dwg = ezdxf.readfile('write_Lines.dxf') dwg = io.open('write_Lines.dxf', mode='rt') outputText = dwg.read() elif (str(geometryType) == 'Point'): #copied from writeDXF_StrInput.py dwg = ezdxf.new('R2010') flag = dwg.blocks.new(name='FLAG') msp = dwg.modelspace() flag.add_point((0, 0), dxfattribs={'color': 2}) AttribInfo = result['features'][0]['properties'] Attribs = AttribInfo.keys() #add attribute definitions x = 0.5 y = -1 for i in Attribs: property = i flag.add_attdef(str(property), (x, y), { 'height': 0.5, 'color': 3 }) y = y - 1.5 # Now I can populate the drawing object and create the dxf file # get each coordinate # get the attribute information and store with each point points = [] x = 0.5 for i in range(numFeats): a_point = result['features'][i]['geometry']['coordinates'] att_info_dict = result['features'][i]['properties'] points.append( a_point ) #a list of lists, each coordinate is of type float msp.add_auto_blockref('FLAG', a_point, att_info_dict) dwg.saveas('write_point_att1.dxf') dwgT = io.open('write_point_att1.dxf', mode='rt') outputText = dwgT.read() else: outputText = '' output = outputText return output
from HersheyFonts import HersheyFonts from gerberex import DrillComposition from gerberex import GerberComposition from tabulate import tabulate from frame_generator import generate_pcb_frame, generate_pcb_bridges, generate_outer_frame ELEMENTS_DIR = "input/elements/" INPUT_DIR = "input/base_variant/" OUTPUT_DIR = "output_stage1/" TEMP_DIR = "temp/" cutout_width = 2.54 # mm frame_width = 5 # mm board_cutout_doc = ezdxf.new('R2010') board_cutout_msp = board_cutout_doc.modelspace() board_info_doc = ezdxf.new('R2010') board_info_msp = board_info_doc.modelspace() font = HersheyFonts() font.load_default_font() today = date.today() class GerberSettings: format = [3, 3] units = "metric" zero_suppression = "leading"
# Copyright (c) 2016-2019 Manfred Moitzi # License: MIT License import ezdxf import os IMAGE_PATH = 'mycat.jpg' ABS_IMAGE_PATH = os.path.abspath(IMAGE_PATH) doc = ezdxf.new('R2004') # image requires the DXF 2000 or newer format my_image_def = doc.add_image_def(filename=ABS_IMAGE_PATH, size_in_pixel=(640, 360)) # image definition is like a block definition msp = doc.modelspace() # add first image, image is like a block reference (INSERT) msp.add_image(image_def=my_image_def, insert=(2, 1), size_in_units=(6.4, 3.6), rotation=0) # add first image msp.add_image(image_def=my_image_def, insert=(4, 5), size_in_units=(3.2, 1.8), rotation=30) # rectangular boundaries image = msp.add_image(image_def=my_image_def, insert=(10, 1), size_in_units=(6.4, 3.6), rotation=0) image.set_boundary_path([(50, 50), (600, 300)])
# Copyright (c) 2020-2021, Manfred Moitzi # License: MIT License import pathlib import ezdxf DIR = pathlib.Path('~/Desktop/Outbox').expanduser() doc = ezdxf.new('R2010', units=6) msp = doc.modelspace() gdat = msp.new_geodata() gdat.setup_local_grid(design_point=(0, 0), reference_point=(1718030, 5921664)) msp.add_line((0, 0), (100, 0)) doc.set_modelspace_vport(50, center=(50, 0)) doc.saveas(DIR / 'geodata_local_grid.dxf')
def doc(): d = ezdxf.new() d.layers.new('Test1') return d
def sections(): dwg = ezdxf.new('R12') return Sections(load_dxf_structure(internal_tag_compiler(TEST_HEADER)), dwg)
# Copyright (c) 2019 Manfred Moitzi # License: MIT License import ezdxf from ezdxf.tools.standards import styles dwg = ezdxf.new('R12', setup=True) msp = dwg.modelspace() y = 0 height = .5 line_height = 1.5 for style, font in styles(): msp.add_text(style, {'style': style, 'height': height}).set_pos((0, y)) y += height * line_height dwg.saveas('using_all_text_styles.dxf')
def drawing(request): return ezdxf.new(request.param)
5000), # center of viewport in paper_space units, scale = 1:50 size=(5000, 2500), # viewport size in paper_space units, scale = 1:50 view_center_point=( 60, 40), # model space point to show in center of viewport in WCS view_height= 20, # how much model space area to show in viewport in drawing units ) layout3.add_circle((0, 0), radius=250) # plot origin layout4 = doc.layouts.new('ezdxf scale 1-1 with offset') layout4.page_setup(size=(297, 210), margins=(10, 10, 10, 10), units='mm', scale=(1, 1), offset=(50, 50)) (x1, y1), (x2, y2) = layout4.get_paper_limits() center_x = (x1 + x2) / 2 center_y = (y1 + y2) / 2 layout4.add_line((x1, center_y), (x2, center_y)) # horizontal center line layout4.add_line((center_x, y1), (center_x, y2)) # vertical center line layout4.add_circle((0, 0), radius=5) # plot origin if __name__ == '__main__': doc = ezdxf.new('R2000') draw_raster(doc) setup_active_viewport(doc) layout_page_setup(doc) doc.saveas(FILENAME) print(f'DXF file "{FILENAME}" created.')
def new_doc(): # setting up a drawing is expensive - use as few test methods as possible return ezdxf.new('R2000')
def ac1009(): return ezdxf.new('AC1009')
def ac1015(): return ezdxf.new('AC1015')
def doc(): return ezdxf.new('R2000')