def dxf2csv(file_name): with open(file_name + '.csv', 'wb') as csvfile: # Create csv writer using commas as delimiter writer = csv.writer(csvfile, delimiter=',') # Put all start and end points of lines into csv file dwg = ezdxf.readfile(file_name + '.dxf') for entity in dwg.entities: if entity.dxftype() == 'LINE': print entity.dxf.start print entity.dxf.end print "\n" row = [entity.dxf.start[0], entity.dxf.start[1], entity.dxf.start[2], entity.dxf.end[0], entity.dxf.end[1], entity.dxf.end[2]] writer.writerow(row)
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 __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.tree_file = QtGui.QTreeView() self.setCentralWidget(self.tree_file) self.show() self.colorModel = ColorModel() self.colorDict = kelly_colors self.colorModel.addColors(self.colorDict,colors) self.dxffileName = filename self.headers = ('Name','Show', 'Voltage', 'Rate', 'Angle', 'Step', 'Time', 'Length', 'Closed', 'Color', 'Type') self.dxf = ezdxf.readfile(def_dxf_file) self.model = TreeModel(self.headers, self.dxf, parent=self) self.tree_file.setModel(self.model) self.tree_file.setDragDropMode( QtGui.QAbstractItemView.InternalMove ) self.tree_file.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection ) for col in [self.headers.index(col) for col in ['Closed', 'Show']]: self.tree_file.setItemDelegateForColumn(col,CheckBoxDelegate(self)) for col in [self.headers.index(col) for col in ['Voltage', 'Rate', 'Angle', 'Step']]: self.tree_file.setItemDelegateForColumn(col,DoubleSpinBoxDelegate(self)) self.tree_file.setItemDelegateForColumn(self.model.col('Color'),ColorDelegate(self)) self.tree_file.expandAll() for col in [self.headers.index(col) for col in ['Closed', 'Show']]: root = self.tree_file.rootIndex() for i in range(0,self.model.rowCount(root)): index = self.model.index(i, col) self.tree_file.openPersistentEditor(index) item = self.model.getItem(index) for ch in range(0,item.childCount()): index2 = self.model.index(ch, col, self.model.index(i)) self.tree_file.openPersistentEditor(index2) for column in range(self.model.columnCount()): self.tree_file.resizeColumnToContents(column) screen = QtGui.QDesktopWidget().screenGeometry() print('(set to minimum expanding?)') self.setGeometry(int(screen.width()/3), int(screen.height()/3), screen.width()/2, screen.height()/2) # for col in [self.headers.index(col) for col in ['Color']]: self.tree_file.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.tree_file, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.doMenu) print('make last column just as wide as needed')
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 translation_dxf(fromfile, tofile, x, y): starttime = time.time() dwg = readfile(fromfile) #print "dwg is type:" + str(type(dwg)) translation_x_y(dwg, x, y) dwg.saveas(tofile) endtime = time.time() print('Operation time: %.2f seconds' % (endtime-starttime) )
def main(filename): dwg = ezdxf.readfile(filename) if dwg.dxfversion < 'AC1015': print('DXF Version >= AC1015 required') sys.exit() rootdict = dwg.rootdict db = dwg.entitydb layouts = dwg.dxffactory.wrap_handle(rootdict['ACAD_LAYOUT']) print(list(layouts.keys()))
def dxf2nativen(filename): """Generate a dictionary of {k=type: v=attribs} from dxf entities.""" drawlist = [] dwg = ezdxf.readfile(filename) for e in dwg.modelspace(): # e = dxf entity if e.dxftype() == 'POINT': coords = (e.dxf.location, 2.2222) drawlist.append({'gc': (coords, "red")}) return drawlist
def dxf2nativec(filename): """Generate a dictionary of {k=type: v=attribs} from dxf entities.""" drawlist = [] dwg = ezdxf.readfile(filename) for e in dwg.modelspace(): # e = dxf entity if e.dxftype() == 'CIRCLE': coords = (e.dxf.center, e.dxf.radius) drawlist.append({'gc': (coords, "blue")}) return drawlist
def find_unused_blocks(filename): try: doc = ezdxf.readfile(filename, legacy_mode=True) except IOError: pass except ezdxf.DXFError as e: print('\n' + '*' * 40) print('FOUND DXF ERROR: {}'.format(str(e))) print('*' * 40 + '\n') else: _find_unused_blocks(doc)
def iter_2D_plan(): import ezdxf doc = ezdxf.readfile(_2D_PLAN) msp = doc.modelspace() count = 0 for e in msp: e.dxftype() count += 1 print( f'Iterated {count} entities in modelspace (AEC Plan Elev Sample.dxf).') del doc
def test_reload_dimtxsty(doc, tmpdir): filename = tmpdir.join("dim_text_style.dxf") doc.saveas(filename) # reload file doc2 = ezdxf.readfile(filename) style = doc2.styles.get(TEXTSTYLE_NAME) assert style.dxf.font == FONT_NAME dimstyle = doc2.dimstyles.get(DIMSTYLE_NAME) assert dimstyle.dxf.dimtxsty == TEXTSTYLE_NAME
def print_layer_names(filename): """ Print all layers in a DXF file that contain artwork. Layer 0 is added as an empty layer. Args: filename (str): name of DXF file """ dxf = ezdxf.readfile(filename) layers = get_layer_names(dxf) for i, l in enumerate(layers): print('{0}: {1}'.format(i, l))
def test_open_R2000_with_xdata(): filename = os.path.join(BASEDIR, DATADIR, "bin_dxf_r2000.dxf") doc = ezdxf.readfile(filename) assert "Model" in doc.layouts, "Model space not found" assert "Layout1" in doc.layouts, "Paper space not found" assert doc.dxfversion == "AC1015" msp = doc.modelspace() text = msp.query("TEXT").first assert text.dxf.text == "ezdxf" hyperlink, description, location = text.get_hyperlink() assert hyperlink == "http://ezdxf.mozman.at" msp.add_line((0, 0), (10, 3))
def test_write_and_read_metadata(doc, tmp_path): custom = "CUSTOM" metadata = doc.ezdxf_metadata() del metadata[CREATED_BY_EZDXF] metadata[custom] = custom doc.saveas(tmp_path / "ez.dxf") doc2 = ezdxf.readfile(tmp_path / "ez.dxf") metadata2 = doc2.ezdxf_metadata() assert metadata2[WRITTEN_BY_EZDXF].startswith(ezdxf.__version__) assert CREATED_BY_EZDXF not in metadata2, "should be deleted" assert metadata2[custom] == custom, "expected custom metadata"
def main(filename): ezdxf.options['DEBUG'] = True drawing = ezdxf.readfile(filename) folder = os.path.dirname(filename) dbcontent = os.path.join(folder, 'dbcontent.txt') print('writing content to: %s' % dbcontent) with open(dbcontent, 'wt') as stream: drawing.entitydb.dumpcontent(stream, verbose=False) dbcollisions = os.path.join(folder, 'dbcollisions.txt') print('writing collisions to: %s' % dbcollisions) with open(dbcollisions, 'wt') as stream: drawing.entitydb.dumpcollisions(stream)
def test_reload_dxf_with_empty_group_content(doc, tmp_path): delete_G1_content(doc) doc.saveas(tmp_path / GROUPS) del doc reload = ezdxf.readfile(tmp_path / GROUPS) assert len(reload.groups) == 2 (name1, g1), (name2, g2) = reload.groups assert name1 == "G1" assert len(g1) == 0, "empty group still exist" assert name2 == "G2" assert len(g2) == 8
def print_stats(filename): print('opening DXF file: {}'.format(filename)) start_time = time.time() dwg = ezdxf.readfile(filename) end_time = time.time() print('time for reading: {:.1f} seconds'.format(end_time - start_time)) print("DXF version: {}".format(dwg.dxfversion)) print("Database contains {} entities.".format(len(dwg.entitydb))) polylines = dwg.entities.query('POLYLINE') polyface_count, polymesh_count = count_meshes(polylines) print("PolyFaceMeshes: {}".format(polyface_count)) print("PolygonMeshes {}".format(polymesh_count))
def __init__(self, fname_dxf): '''arr_sgm - segments array [[[x,y,z],[x1,y1,z1]]...] arr_prp - properties vector [l0, l0, ... l1] dct_prp - properties dictionary {l0:{...}, l1:{...}''' seg_dt = np.dtype([('seg', float, (2,3)), ('prp', int, 1)]) self.seg_dt = seg_dt self.dwg = ezdxf.readfile(fname_dxf) self.seg_arr = np.array([], dtype = seg_dt) self.prp_dict = collections.OrderedDict({'glob':{}, 'loc':{}}) self.model = collections.OrderedDict({})
def find_coordinates(filename='test.dxf', layer_name='0'): dwg_dxf = ezdxf.readfile(filename) for e in dwg_dxf.entities: if layer_name in e.get_dxf_attrib( key='layer') and e.dxftype() == 'LWPOLYLINE': polygon_points = [] for i in e.get_rstrip_points(): polygon_points.append(i) print polygon_points
def iter_3D_model(): import ezdxf dwg = ezdxf.readfile( filename=r"D:\Source\dxftest\CADKitSamples\fanuc-430-arm.dxf") msp = dwg.modelspace() count = 0 for e in msp: e.dxftype() count += 1 print('Iterated {} entities in modelspace (fanuc-430-arm.dxf).'.format( count)) del dwg
def test_open_R2000_with_xdata(): filename = os.path.join(BASEDIR, DATADIR, 'bin_dxf_r2000.dxf') doc = ezdxf.readfile(filename) assert 'Model' in doc.layouts, 'Model space not found' assert 'Layout1' in doc.layouts, 'Paper space not found' assert doc.dxfversion == 'AC1015' msp = doc.modelspace() text = msp.query('TEXT').first assert text.dxf.text == 'ezdxf' hyperlink, description, location = text.get_hyperlink() assert hyperlink == 'http://ezdxf.mozman.at' msp.add_line((0, 0), (10, 3))
def test_interpreting_geodata(georeferenced_test_file_path): # It is unclear how to create a georeferenced file from scratch. Copying # # every GeoData attribute and document header value across was not enough # # for AutoCAD to correctly interpret the coordinates. doc = ezdxf.readfile(georeferenced_test_file_path) geodata = doc.modelspace().get_geodata() assert geodata.decoded_units() == ('in', 'in') # inches coordinate_system_definition = geodata.coordinate_system_definition geodata.coordinate_system_definition = '' with pytest.raises(ezdxf.InvalidGeoDataException): geodata.get_crs() geodata.coordinate_system_definition = coordinate_system_definition assert geodata.get_crs() == (27700, True) # the outline of the Houses of Parliament in London, WCS coordinates are # meaningless, but the cad file is georeferenced as epsg:27700 expected_geo_points = [(530207.5677217417, 179366.7895852687), (530304.7243275082, 179354.44795162012), (530337.0722795193, 179620.5081263125), (530285.502052045, 179626.77810356658), (530288.2604343889, 179649.46565077276), (530260.6778594478, 179652.81917713786), (530256.9625486559, 179629.5648430319), (530266.9241695277, 179627.97328950214), (530259.8925073204, 179577.1375901363), (530179.7793595218, 179598.3848030573), (530174.8000936891, 179519.37903558338), (530189.905505017, 179515.41460442453), (530184.6203071928, 179495.27676273056), (530217.9628916974, 179486.52596620753), (530223.1861964873, 179485.42147930583), (530207.5677217417, 179366.7895852687)] expected_transformation = Matrix44( (0.02154042164237322, -0.013459949311523403, 0.0, 0.0), (0.013459949311523403, 0.02154042164237322, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (529635.6280343985, 179575.4070305015, 0.0, 1.0)) transformation, epsg = geodata.get_crs_transformation() assert epsg == 27700 assert all( math.isclose(x1, x2) for x1, x2 in zip(transformation, expected_transformation)) entity = list(doc.modelspace().query('LWPOLYLINE'))[0] georeferenced_entity = entity.transform(transformation) transformed_points = georeferenced_entity.get_points(format='xy') assert len(transformed_points) == len(expected_geo_points) assert all( Vec3(x1).isclose(Vec3(x2)) for x1, x2 in zip(transformed_points, expected_geo_points))
def __init__(self, fname_dxf): '''arr_sgm - segments array [[[x,y,z],[x1,y1,z1]]...] arr_prp - properties vector [l0, l0, ... l1] dct_prp - properties dictionary {l0:{...}, l1:{...}''' seg_dt = np.dtype([('seg', float, (2, 3)), ('prp', int, 1)]) self.seg_dt = seg_dt self.dwg = ezdxf.readfile(fname_dxf) self.seg_arr = np.array([], dtype=seg_dt) self.prp_dict = collections.OrderedDict({'glob': {}, 'loc': {}}) self.model = collections.OrderedDict({})
def test_get_acis_data_from_surfaces(): dwg = ezdxf.readfile(SURFACES) msp = dwg.modelspace() with open(DXF_PATH / "All_Surfaces_R2010.sat", "wt") as f: for surface in msp.query( "SURFACE SWEPTSURFACE REVOLVEDSURFACE LOFTEDSURFACE EXTRUDEDSURFACE" ): f.write(DELIMITER) f.write(str(surface) + ":") f.write(DELIMITER) f.write("\n".join(surface.acis_data))
def test_get_acis_data_from_surfaces(): dwg = ezdxf.readfile(FILE) msp = dwg.modelspace() with open(os.path.join(DXFPATH, "All_Surfaces_R2010.sat"), 'wt') as f: for surface in msp.query( 'SURFACE SWEPTSURFACE REVOLVEDSURFACE LOFTEDSURFACE EXTRUDEDSURFACE' ): f.write(DELIMITER) f.write(str(surface) + ':') f.write(DELIMITER) f.write('\n'.join(surface.get_acis_data()))
def iter_2D_plan(): import ezdxf dwg = ezdxf.readfile( filename=r"D:\Source\dxftest\CADKitSamples\AEC Plan Elev Sample.dxf") msp = dwg.modelspace() count = 0 for e in msp: e.dxftype() count += 1 print('Iterated {} entities in modelspace (AEC Plan Elev Sample.dxf).'. format(count)) del dwg
def open_dxf(self, filename): try: self.doc = ezdxf.readfile(filename) return True except IOError: print(f'Not a DXF file or a generic I/O error.') # sys.exit(1) return False except ezdxf.DXFStructureError: print(f'Invalid or corrupted DXF file.') # sys.exit(2) return False
def save_as(name): filename = SRCDIR / name print(f"opening DXF file: {filename}") start_time = time.time() doc = ezdxf.readfile(filename) msp = doc.modelspace() end_time = time.time() print(f"time for reading: {end_time - start_time:.1f} seconds") print(f"DXF version: {doc.dxfversion}") print(f"Database contains {len(doc.entitydb)} entities.") polyfaces = ( polyline for polyline in msp.query("POLYLINE") if polyline.is_poly_face_mesh ) # create a new documents doc1 = ezdxf.new() msp1 = doc1.modelspace() doc2 = ezdxf.new() msp2 = doc2.modelspace() for polyface in polyfaces: b = MeshVertexMerger.from_polyface(polyface) b.render_mesh( msp1, dxfattribs={ "layer": polyface.dxf.layer, "color": polyface.dxf.color, }, ) b.render_polyface( msp2, dxfattribs={ "layer": polyface.dxf.layer, "color": polyface.dxf.color, }, ) new_filename = OUTDIR / ("mesh_" + name) print(f"saving as mesh DXF file: {new_filename}") start_time = time.time() doc1.saveas(new_filename) end_time = time.time() print(f"time for saving: {end_time - start_time:.1f} seconds") new_filename = OUTDIR / ("recreated_polyface_" + name) print(f"saving as polyface DXF file: {new_filename}") start_time = time.time() doc2.saveas(new_filename) end_time = time.time() print(f"time for saving: {end_time - start_time:.1f} seconds")
def layers2seq(fname, req_layer): '''layer naming convention: A#XX#Y#ZZ~comment A - layername XX- sequence_number Y - column number 0 - flat, 1-XY, 2-UV ZZ- section number, might be empty ~comment ''' key = r'(^{})#(\d+)#([01_])#((\d+)?)(.*)'.format(req_layer) layer_list = [] seq_list = [] seq_layer_dict = nested_dict() if os.path.isfile(fname): dwg = ezdxf.readfile(fname) for layer in dwg.layers: split_layer_name = re.findall(key, layer.dxf.name, re.IGNORECASE) if split_layer_name: seq_idx = split_layer_name[0][1] col_idx = split_layer_name[0][2] seq_layer_dict[seq_idx][col_idx][layer.dxf.name] = [] if seq_layer_dict: seq_layer_dict = collections.OrderedDict( sorted(seq_layer_dict.items(), key=lambda x: x[0])) print('{:-^79}'.format('MODEL STRUCTURE')) for var in print_nested(seq_layer_dict, []): if var: print(var) for seq_key in sorted(seq_layer_dict.keys()): col_list = [] for plane_key in sorted(seq_layer_dict[seq_key].keys()): layer_list = [] for layer in sorted( seq_layer_dict[seq_key][plane_key].keys()): layer_list.append(layer) col_list.append(layer_list) seq_list.append(col_list) else: print('cannot find requested pattern: {}'.format(req_layer)) print('avaliable layers:') for layer in dwg.layers: print(' {}'.format(layer.dxf.name)) else: print('cannot find file: {}'.format(fname)) return seq_list, seq_layer_dict
def test_write_and_read_binary_dxf(tmpdir_factory): filename = str(tmpdir_factory.getbasetemp().join("bin.dxf")) with r12writer(filename, fmt="bin") as dxf: dxf.add_line((0, 0), (17, 23)) doc = ezdxf.readfile(filename) line = doc.modelspace()[0] assert line.dxftype() == "LINE" assert line.dxf.start == (0, 0, 0) assert line.dxf.end == (17, 23, 0) if os.path.exists(filename): os.remove(filename)
def get_layer_names(self, path, exclude=None): if exclude is None: exclude = () if isinstance(exclude, str): exclude = (exclude, ) exclude = exclude + ("0", "Defpoints") doc = ezdxf.readfile(path) names = [layer.dxf.name for layer in doc.layers] names = [name for name in names if name not in exclude] return names
def test_block_import(filename, tmpdir): source_dwg = ezdxf.readfile(filename) target_dwg = ezdxf.new(source_dwg.dxfversion) importer = ezdxf.Importer(source_dwg, target_dwg) importer.import_blocks(query='CustomBlock1') importer.import_modelspace_entities() filename = str(tmpdir.join('custom_blocks_import.dxf')) try: target_dwg.saveas(filename) except ezdxf.DXFError as e: pytest.fail("DXFError: {0} for DXF version {1}".format( str(e), target_dwg.dxfversion)) assert os.path.exists(filename)
def find_unused_blocks(filename): try: doc = ezdxf.readfile(filename) except IOError: return except ezdxf.DXFStructureError: try: print('Using recover mode.') doc, auditor = recover.readfile(filename) except ezdxf.DXFStructureError: print(f'DXF structure error!') return _find_unused_blocks(doc)
def __init__(self): """Iniciamos la clase OrigenDXF haciendo que consulte la clase de XML, donde le manda el archivo de origen. Trabajaremos con dos modulos el de lectura de polylineas(readPolyline) y el solo puntos (readPoint)""" # Solo corro para un archivo, posteriormente se debera de incrementar los paths FileWork = Rxml.readxml()[0] # Obtengo el Nombre del archivo separando las barras. self.fileDxf = FileWork self.NameFile = (FileWork.split("\\")[-1])[:-4] file = DXF.readfile(FileWork) self.Sheet = file.modelspace() UnitCreate = file.header['$MEASUREMENT'] UnitPrecition = file.header['$LUNITS'] VersionFile = file.dxfversion
def audit(filename: str, ignore_zero_pointers: bool = False) -> None: try: dwg = readfile(filename, legacy_mode=True) except IOError: print("Unable to read DXF file '{}'.".format(filename)) sys.exit(1) except DXFError as e: print(str(e)) sys.exit(2) auditor = dwg.auditor() errors = auditor.run() auditor.print_error_report(errors)
def run(start): if start > 0: start -= 1 names = list(chain(glob.glob(DIR1), glob.glob(DIR2))) names = names[start:] count = 0 for filename in names: count += 1 print("processing: {}/{} file: {}".format(count+start, len(names)+start, filename)) doc = ezdxf.readfile(filename, legacy_mode=LEGACY_MODE) auditor = Auditor(doc) if len(auditor): auditor.print_error_report(auditor.errors)
def parse_dxf(data, material_speed, name, ws): with tempfile.NamedTemporaryFile() as fs: fs.write(bytes(data, 'UTF-8')) dxf = ezdxf.readfile(fs.name) modelspace = dxf.modelspace() if config["save_dxf_to"]: try: dxf.saveas(os.path.join(config["save_dxf_to"], strftime(name + " %Y-%m-%d %H.%M.%S.dxf", gmtime()))) except: printer.color_print(config["save_dxf_fail_message"], target=config["save_dxf_to"], color=ansi_colors.RED) if config["save_dxf_fail_user_message"]: serve_connection({ "action": "notification", "title": "Failed to save file", "text": config["save_dxf_fail_user_message"] }, ws) totaldist = 0 for el in modelspace: if el.dxftype() == "POLYLINE": newpoint = 0 oldpoint = 0 # for each point on POLYLINE for point in el.vertices(): oldpoint = newpoint newpoint = point.dxf.location if oldpoint != 0: totaldist += dist(newpoint, oldpoint) elif el.dxftype() == "LINE": totaldist += dist(el.dxf.start, el.dxf.end) elif el.dxftype() == "CIRCLE": totaldist += 2 * math.pi * el.dxf.radius elif el.dxftype() == "ARC": circumference = 2 * math.pi * el.dxf.radius arcportion = abs(el.dxf.start_angle - el.dxf.end_angle) / 360 totaldist += circumference * arcportion # elif el.dxftype() == "SPLINE": else: printer.color_print("Unsupported object of type {type} found. Ommitting.", type=el.dxftype(), color=ansi_colors.RED) t = round(totaldist / material_speed + config["initmove"]) / 60 if args.loud: printer.color_print("Estimate: {time}s", time=t*60) serve_connection({ "action": "dxf_estimate", "time": t }, ws) return t
def __init__(self, filename, area, spec_line_layer, spec_text_layer, exc_line_layer, exc_text_layer): self.doc = ezdxf.readfile(filename) self.area = area pre, ext = os.path.splitext(filename) csv_path = pre + '.csv' self.georef_transform = transform_from_csv(csv_path) self.spec_regions = self._get_regions(spec_line_layer, spec_text_layer) self.exc_regions = self._get_regions(exc_line_layer, exc_text_layer) self._transform_regions(self.spec_regions) self._transform_regions(self.exc_regions)
def optimize(filename, new_filename): print('opening DXF file: {}'.format(filename)) start_time = time.time() dwg = ezdxf.readfile(filename) end_time = time.time() print('time for reading: {:.1f} seconds'.format(end_time - start_time)) print("DXF version: {}".format(dwg.dxfversion)) print("Database contains {} entities.".format(len(dwg.entitydb))) polyfaces = (polyline for polyline in dwg.entities.query('POLYLINE') if polyline.is_poly_face_mesh) optimize_polyfaces(polyfaces) print('saving DXF file: {}'.format(new_filename)) start_time = time.time() dwg.saveas(new_filename) end_time = time.time() print('time for saving: {:.1f} seconds'.format(end_time - start_time))
def test_open_proe_ac1018(self): dwg = ezdxf.readfile("D:\Source\dxftest\ProE_AC1018.dxf") modelspace = dwg.modelspace() # are there entities in model space self.assertEqual(17, len(modelspace)) # can you get entities lines = modelspace.query('LINE') self.assertEqual(12, len(lines)) # is owner tag correct first_line = lines[0] self.assertEqual(modelspace.layout_key, first_line.dxf.owner) # is paper space == 0 self.assertEqual(0, first_line.dxf.paperspace)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.tree_file = QtGui.QTreeView() self.setCentralWidget(self.tree_file) self.show() self.colorModel = ColorModel() self.colorDict = kelly_colors self.colorModel.addColors(self.colorDict) self.dxffileName = filename self.headers = ("Name", "Show", "Voltage", "Rate", "Angle", "Step", "Time", "Closed", "Color", "Type") self.dxf = ezdxf.readfile(def_dxf_file) self.model = TreeModel(self.headers, self.dxf, parent=self) self.tree_file.setModel(self.model) self.tree_file.setDragDropMode(QtGui.QAbstractItemView.InternalMove) self.tree_file.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) for col in [self.headers.index(col) for col in ["Closed", "Show"]]: self.tree_file.setItemDelegateForColumn(col, CheckBoxDelegate(self)) for col in [self.headers.index(col) for col in ["Voltage", "Rate", "Angle", "Step"]]: self.tree_file.setItemDelegateForColumn(col, DoubleSpinBoxDelegate(self)) self.tree_file.setItemDelegateForColumn(self.model.col("Color"), ColorDelegate(self)) self.tree_file.expandAll() for column in range(self.model.columnCount()): self.tree_file.resizeColumnToContents(column) screen = QtGui.QDesktopWidget().screenGeometry() print("(set to minimum expanding?)") self.setGeometry(int(screen.width() / 3), int(screen.height() / 3), screen.width() / 2, screen.height() / 2) # for col in [self.headers.index(col) for col in ['Color']]: self.tree_file.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.tree_file, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.doMenu) print("make last column just as wide as needed")
def generate_dxf_entities(self): if not ezdxf: return dwg = ezdxf.readfile(self.dxf.path) modelspace = dwg.modelspace() for e in modelspace: if e.dxftype() == "LWPOLYLINE": geometry = [list(i)[:2] for i in e.get_points()] elif e.dxftype() == "LINE": geometry = [e.dxf.start,e.dxf.end] else: continue dxf,new = DXFEntity.objects.get_or_create( dxftype = e.dxftype(), points = json.dumps([[round(i) for i in p] for p in geometry]) ) if new: print("New DXFEntity: %s"%dxf)
def main(inputfile, flags): """ :param inputfile: Name of a DXF file to read :param flags: command line flags """ dwg = ezdxf.readfile(inputfile) # fix entities with negative extrusion direction negative_extrusion_entities = validate_negative_extrusion(dwg, flags) # check for non-planar in Z entity_planes = validate_z_plane(dwg, flags) # flatten all to z=0.0 otherwise we crash the waterjet head :( non_z_zero = validate_z_zero(dwg, flags) # adjust by scaling factor scale(dwg, flags) if negative_extrusion_entities > 0: print('VALIDATION ERROR: Found {0} entities with negative extrusion direction' .format(negative_extrusion_entities)) if entity_planes > 1: print('VALIDATION ERROR: Found {0} non-planar entities!'.format(entity_planes)) if non_z_zero > 0: print('VALIDATION ERROR: Found {0} entities not at z=0.0'.format(non_z_zero)) if negative_extrusion_entities == 0 and entity_planes == 1 and non_z_zero == 0: print('SUCCESS: no DXF format errors found, no repair needed!') if 'unit_conversion' in flags: (file_root, file_ext) = os.path.splitext(inputfile) outputfile = file_root + ' ' + flags['unit_conversion'] + file_ext dwg.saveas(outputfile) return else: (file_root, file_ext) = os.path.splitext(inputfile) outputfile = file_root + ' repaired' + file_ext dwg.saveas(outputfile) print('Wrote repaired file as {0}'.format(outputfile))
def main(inputfile, outputfile): """ Mirror all CIRCLE and ARC entities if their centre coordinates are negative in Z axis :param inputfile: Name of a DXF file to read :param outputfile: Name of a DXF file to write """ dwg = ezdxf.readfile(inputfile) for e in dwg.entities: (x,y,z) = e.dxf.extrusion if z < 0: if e.dxftype() == 'CIRCLE': e.dxf.center = mirror_coord(e.dxf.center) elif e.dxftype() == 'ARC': start_angle = e.dxf.start_angle end_angle = e.dxf.end_angle e.dxf.start_angle = mirror(end_angle) e.dxf.end_angle = mirror(start_angle) e.dxf.center = mirror_coord(e.dxf.center) e.dxf.extrusion = (0,0,1.0) dwg.saveas(outputfile)
import ezdxf pts = [(323380.91750022338, 5184999.7255775109, 0.0), (323377.13033454702, 5184994.8609992303, 0.0), (323375.96284645743, 5184992.1182727059, 0.0), (323374.72169714782, 5184989.8344467692, 0.0), (323374.17676884111, 5184988.5392300664, 0.0), (323373.39893951337, 5184986.7871434148, 0.0), (323372.92717616714, 5184984.9566230336, 0.0), (323372.37727835565, 5184982.897411068, 0.0), (323371.90899244603, 5184981.601685036, 0.0), (323375.99291780719, 5184981.3014478451, 0.0), (323375.99841245974, 5184977.7365302956, 0.0), (323377.32736607571, 5184977.6150565967, 0.0), (323377.76792070246, 5184970.3801041171, 0.0), (323378.56378788338, 5184967.413698026, 0.0), (323379.38490772923, 5184964.9500029553, 0.0)] drawing = ezdxf.new('AC1015') modelspace = drawing.modelspace() modelspace.add_polyline3d(pts) drawing.saveas('test.dxf') dxf = ezdxf.readfile('test.dxf') for entity in dxf.entities: if entity.dxftype() == 'POLYLINE': for pt in entity.points(): pass # Entities iterator is OK.
def add_square(dwg): # Get base square -1000 to 1000 square_dxf = readfile('Square.dxf')
def main(filename): print('reading file ...') dwg = ezdxf.readfile(filename) print('counting elements ...') result = count_elements(dwg.entitydb) print_result(result)
def library(request): now = datetime.datetime.now() logging.basicConfig(filename='log/library.log', level=logging.INFO) logging.info( "" ) logging.info(' #------------------------------------------------# ') logging.info( now ) logging.info(' # Begin Views Function ==> Library ezdxf ') logging.info( "" ) # dxf = ezdxf.readfile("dxffiles/habitacion.dxf"); # dxf = ezdxf.readfile("dxffiles/pared.dxf"); dxf = ezdxf.readfile("dxffiles/hostel.dxf") logging.info( "" ) logging.info(' #------------------------------------------------# ') logging.info(' # DXF information: ') logging.info(' # Version [ %s ] ', dxf.dxfversion) dxf_version = dxf.dxfversion; # header_var_count = len(dxf.header) # dict of dxf header vars # logging.info(' # Nº vars header [ %d ] ', header_var_count) layer_count = len(dxf.layers) # collection of layer definitions logging.info(' # Nº vars layer [ %d ] ', layer_count) block_definition_count = len(dxf.blocks) # dict like collection of block definitions logging.info(' # Nº vars count definition [ %d ] ', block_definition_count) entity_count = len(dxf.entities) logging.info(' # Nº vars entities [ %d ] ', entity_count) logging.info(' #------------------------------------------------# ') modelspace = dxf.modelspace() i = 0 for e in modelspace: tipo = e.dxftype() logging.info( " modelspace [ %d ]" %i) logging.info( " tipo %s", tipo ) logging.info(' # Layer [ %s ] ', e.dxf.layer) logging.info( "" ) # logging.info(' # Handle [ %s ] ', e.dxf.handle) # logging.info(' # Color [ %s ] ', e.dxf.color) # logging.info(' # Paperspace [ %s ] ', e.dxf.paperspace) logging.info( "" ) if e.dxftype() == 'POLYLINE': logging.info( "" ) logging.info(' #-------------[ POLYLINE ]-[%d] ----------------# ' %i) logging.info( "" ) # logging.info(' # NAME [ %s ] ', e.dxf.name) logging.info(' # Layer [ %s ] ', e.dxf.layer) # if e.dxftype() == 'A-WALL': # logging.info(' ################################################## ') # logging.info(' ################## A-WALL ######################## ') # logging.info(' ################################################## ') logging.info(' # Handle [ %s ] ', e.dxf.handle) logging.info(' # Color [ %s ] ', e.dxf.color) logging.info(' # Paperspace [ %s ] ', e.dxf.paperspace) logging.info(' # Extrusion [ %s ] ', e.dxf.extrusion) logging.info(' # Elevation [ %s ] ', e.dxf.elevation) logging.info(' # Flags [ %d ] ', e.dxf.flags) if e.dxf.flags == 64: logging.info(' ## POLYLINE_POLYFACE_MESH This Polyline is a polyface mesh ' ) logging.info(' # Df start Width [ %d ] ', e.dxf.default_start_width) logging.info(' # Df end Width [ %d ] ', e.dxf.default_end_width) logging.info(' # m_count [ %d ] ', e.dxf.m_count) logging.info(' # n_count [ %d ] ', e.dxf.n_count) logging.info(' # m_smooth_density [ %d ] ', e.dxf.m_smooth_density) logging.info(' # n_smooth_density [ %d ] ', e.dxf.n_smooth_density) logging.info(' # smooth_type [ %d ] ', e.dxf.smooth_type) logging.info( "" ) logging.info(' #------------------------------------------------# ') if e.dxftype() == 'INSERT': logging.info( "" ) logging.info(' #=============[ INSERT ]-[%d] ===================# ' %i) logging.info(' # NAME [ %s ] ', e.dxf.name) logging.info(' # Layer [ %s ] ', e.dxf.layer) logging.info(' # Handle [ %s ] ', e.dxf.handle) logging.info(' # Color [ %s ] ', e.dxf.color) logging.info(' # Paperspace [ %s ] ', e.dxf.paperspace) logging.info(' # Extrusion [ %s ] ', e.dxf.extrusion) logging.info( "" ) logging.info( "" ) logging.info(' #================================================# ') if e.dxftype() == '3DSOLID': logging.info( "" ) logging.info(' #-------------[ 3DSOLID ]-[%d] ----------------# ' %i) logging.info(' # History [ %s ] ', e.dxf.history) logging.info(' # Layer [ %s ] ', e.dxf.layer) logging.info(' # Handle [ %s ] ', e.dxf.handle) logging.info(' # Color [ %s ] ', e.dxf.color) logging.info(' # Paperspace [ %s ] ', e.dxf.paperspace) logging.info( "" ) i = i + 1 # Es lo mismo los entities que los modelspace # for e in dxf.entities: # tipe = e.dxftype() # logging.info(logging.info( " tipe %s", tipe )) # print("DXF Entity: %s\n" % e.dxftype()) logging.info( "" ) logging.info(' # End Views Function ==> Library ezdxf ') logging.info(' #------------------------------------------------# ') logging.info( "" ) return render_to_response('library/dxfhomeezdxf.html', locals())
#!/usr/bin/env python3 # proof of concept hack speed = 10 initmove = 3 import ezdxf import math import inspect # import sys dxf = ezdxf.readfile("many shape types from rhino.dxf") modelspace = dxf.modelspace() totaldist = 0 # calculate distance between two XYZ coords def dist(coord1, coord2): xdist = coord2[0] - coord1[0] ydist = coord2[1] - coord1[1] return math.sqrt(xdist ** 2 + ydist ** 2) # for every element for e in modelspace: # if element is a POLYLINE if e.dxftype() == "POLYLINE": newpoint = 0 oldpoint = 0
import ezdxf, json, sys PATH = 'topo.dxf' dwg = ezdxf.readfile(PATH) modelspace = dwg.modelspace() matches = 0 nope = 0 lines = [] x_max = y_max = -sys.maxint - 1 x_min = y_min = sys.maxint threshold = 1 threshold = threshold for e in modelspace: if e.dxftype() == "LWPOLYLINE": geometry = [list(i)[:2] for i in e.get_points()] x,y = zip(*geometry) x_max = max(x_max,max(x)) y_max = max(y_max,max(y)) x_min = min(x_min,min(x)) y_min = min(y_min,min(y)) lines.append([x,y]) #if geometry[0] == geometry[-1]: #else: # lines['open'].append([x,y]) elif e.dxftype() == "LINE": geometry = [e.dxf.start,e.dxf.end] else: continue def close_loops(): out = False
# display.DisplayShape(my_box, update=True) # start_display() import ezdxf import csv file_name = "example_part_top"; with open(file_name + '.csv', 'wb') as csvfile: # Create csv writer using commas as delimiter writer = csv.writer(csvfile, delimiter=',') # Put all start and end points of lines into csv file dwg = ezdxf.readfile(file_name + '.dxf') for entity in dwg.entities: if entity.dxftype() == 'LINE': print entity.dxf.start print entity.dxf.end print "\n" row = [entity.dxf.start[0], entity.dxf.start[1], entity.dxf.start[2], entity.dxf.end[0], entity.dxf.end[1], entity.dxf.end[2]] writer.writerow(row) # if e.dxftype() == 'POLYLINE': # points = e.points() # for p in points: # print p
def load_dxf(cls, filename, parent=None): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir import ezdxf.modern dxf = ezdxf.readfile(filename) layer_names = [layer.dxf.name for layer in dxf.layers] dialog = qg.QDialog() lw = qg.QListWidget() for item in layer_names: lw.addItem(qg.QListWidgetItem(item)) lw.setSelectionMode(lw.ExtendedSelection) button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') button_ok.clicked.connect(dialog.accept) button_cancel.clicked.connect(dialog.reject) layout = qg.QVBoxLayout() layout_buttons = qg.QHBoxLayout() layout_buttons.addWidget(button_ok) layout_buttons.addWidget(button_cancel) layout.addWidget(lw) layout.addLayout(layout_buttons) dialog.setLayout(layout) result = dialog.exec_() if result: selected_layers = [ item.data( qc.Qt.DisplayRole) for item in lw.selectedItems()] entities = [item for item in dxf.modelspace()] generics = [] for entity in entities: if entity.dxf.layer in selected_layers: if isinstance(entity, ezdxf.modern.graphics.Line): import numpy points = numpy.array( [entity.dxf.start[:2], entity.dxf.end[:2]]) generics.append( GenericLine.gen_from_point_lists( points.tolist(), [])) elif isinstance(entity, ezdxf.modern.graphics.LWPolyline): import numpy points = numpy.array([item for item in entity.get_points()]) points = points[:,:2] if entity.closed: generics.append(GenericPoly.gen_from_point_lists(points.tolist(),[])) else: generics.append(GenericPolyline.gen_from_point_lists(points.tolist(),[])) elif isinstance(entity, ezdxf.modern.graphics.Point): from popupcad.geometry.vertex import DrawnPoint point = DrawnPoint(numpy.array(entity.get_dxf_attrib('location')[:2])) generics.append(point) elif isinstance(entity, ezdxf.modern.graphics.Spline): knots = entity.get_knot_values() control_points = entity.get_control_points() weights = entity.get_weights() n = len(control_points)-1 domain = popupcad.algorithms.spline_functions.make_domain(knots,n*5) points = popupcad.algorithms.spline_functions.interpolated_points(control_points,knots,weights,domain) points = points[:,:2] if entity.closed: generics.append(GenericPoly.gen_from_point_lists(points.tolist(),[])) else: generics.append(GenericPolyline.gen_from_point_lists(points.tolist(),[])) # print(points) else: print(entity) new = cls.new() new.addoperationgeometries(generics) newfile = os.path.splitext(filename)[0]+'.sketch' new.updatefilename(newfile) return filename, new else: return None, None
def read_group(): dwg = ezdxf.readfile('group.dxf') for name, group in dwg.groups: print("GROUP: {}\n".format(name)) for entity in group: print(" ENTITY: {}".format(entity.dxftype()))
# Copyright (C) 2015, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <*****@*****.**>" import sys import os import io from .dxf2html import dxf2html from ezdxf import readfile, options if __name__ == "__main__": options.compress_binary_data = True try: filename = sys.argv[1] except IndexError: print("DXF pretty printer (pp) requires exact one filename of a DXF file.") sys.exit() try: dwg = readfile(filename) except IOError: print("Unable to read DXF file '{}', or invalid DXF file.".format(filename)) sys.exit() html_filename = os.path.splitext(dwg.filename)[0] + '.html' try: with io.open(html_filename, mode='wt', encoding='utf-8') as fp: fp.write(dxf2html(dwg)) except IOError: print("IOError: can not write file '{}'.".format(html_filename))
# for testing # filename = '/Users/nickgravish/popupCAD_files/sketches/Scissor02.dxf' if __name__ == '__main__': filename = sys.argv[1] # get the filename passed in # create the base CAD design file design = popupcad.filetypes.design.Design.new() design.define_layers(popupcad.filetypes.layerdef.LayerDef(*popupcad.filetypes.material2.default_sublaminate)) # load dxf file and select layer names import ezdxf.modern dxf = ezdxf.readfile(filename) layer_names = [layer.dxf.name for layer in dxf.layers] # loop through layer names and load geometry for layer in layer_names: # create the sketch sketch = import_dxf_layer_geometry(dxf, layer) # add the sketch to the design file design.sketches[sketch.id] = sketch # save cad file design.save_yaml(filename + '.cad') # to visualize the result, but can be commented out. app = qg.QApplication(sys.argv)
def copydxf(fromfile, tofile): starttime = time.time() dwg = readfile(fromfile) dwg.saveas(tofile) endtime = time.time() print('copy time: %.2f seconds' % (endtime-starttime) )
def main(filename): dwg = ezdxf.readfile(filename) msp = dwg.modelspace() hatches = msp.query("HATCH[solid_fill==0]") name, ext = os.path.splitext(filename) dump_pattern(name + ".py", hatches)
def load_dxf(cls, filename, parent=None): import ezdxf ezdxf.options.template_dir = popupcad.supportfiledir import ezdxf.modern dxf = ezdxf.readfile(filename) layer_names = [layer.dxf.name for layer in dxf.layers] dialog = qg.QDialog() lw = qg.QListWidget() for item in layer_names: lw.addItem(qg.QListWidgetItem(item)) lw.setSelectionMode(lw.SelectionMode.ExtendedSelection) button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') button_ok.clicked.connect(dialog.accept) button_cancel.clicked.connect(dialog.reject) layout = qg.QVBoxLayout() layout_buttons = qg.QHBoxLayout() layout_buttons.addWidget(button_ok) layout_buttons.addWidget(button_cancel) layout.addWidget(lw) layout.addLayout(layout_buttons) dialog.setLayout(layout) result = dialog.exec_() if result: selected_layers = [ item.data( qc.Qt.ItemDataRole.DisplayRole) for item in lw.selectedItems()] entities = dxf.entities generics = [] for entity in entities: if entity.dxf.layer in selected_layers: if isinstance(entity, ezdxf.modern.graphics.Line): from popupcad.filetypes.genericshapes import GenericLine import numpy points = numpy.array( [entity.dxf.start[:2], entity.dxf.end[:2]]) generics.append( GenericLine.gen_from_point_lists( points.tolist(), [])) elif isinstance(entity, ezdxf.modern.graphics.LWPolyline): from popupcad.filetypes.genericshapes import GenericPolyline from popupcad.filetypes.genericshapes import GenericPoly import numpy points = numpy.array([item for item in entity.get_points()]) points = points[:,:2] if entity.closed: generics.append( GenericPoly.gen_from_point_lists( points.tolist(), [])) else: generics.append( GenericPolyline.gen_from_point_lists( points.tolist(), [])) elif isinstance(entity, ezdxf.modern.graphics.Point): from popupcad.geometry.vertex import DrawnPoint point = DrawnPoint(numpy.array(entity.get_dxf_attrib('location')[:2])) generics.append(point) else: print(entity) new = cls() new.addoperationgeometries(generics) return filename, new else: return None, None