import argparse import ezdxf import json import os.path from dataclasses import dataclass, asdict, fields from dacite import from_dict from typing import List from datetime import datetime @dataclass class Point: x: float y: float @dataclass class Polyline: id: str coords: List[Point] def to_tuple(self): ret = list() for p in self.coords: ret.append( (p.x,p.y) ) return ret @dataclass class Polylines: kabel: List[Polyline] def add_polyline(msp, points:Polyline, dxf_attribs): pts = points.to_tuple() pline = msp.add_lwpolyline(points=pts, dxfattribs=dxf_attribs) pline.rgb = (255, 128, 0) def new_dxf(json_file, dxf_file, out_path): """ creates a new dxf file with a polyline inside which is created by the given json file """ with open(json_file, encoding='utf-8') as fh: data = json.load(fh) anlage = from_dict( data_class=Polylines, data=data ) #print(anlage) # Create a new drawing in the DXF format of AutoCAD 2010 #doc = ezdxf.new('R2018', setup=True) # 1. Bestehende DXF-Datei laden doc = ezdxf.readfile(dxf_file) msp = doc.modelspace() # 2. Layer mit Zeitstempel erstellen (z. B. "Layer_2025-05-07_14-30") timestamp = datetime.now().strftime("Kabel_%Y-%m-%d_%H-%M") if timestamp not in doc.layers: doc.layers.add(name=timestamp, color=7) # add new entities to the modelspace msp = doc.modelspace() # # Beispiel für Text und Polyline # add_text(msp) dxfattribs={"layer": timestamp} for pl in anlage.kabel: add_polyline(msp, pl, dxfattribs) doc.saveas(out_path) if __name__ == '__main__': parser = argparse.ArgumentParser(description='draws a dxf file with the given cable coordinates', prog='drawdxf') parser.add_argument('-j', '--jsonfile', action='store', required=True, help='this json file contains all cables and its coordinates which should be drawn. Saved with an unique timestamp', metavar='myfile.json') parser.add_argument('-d', '--dxf', action='store', required=True, help='this dxf drawing will be copied and the new layer with the cables will be added', metavar='myfile.dxf') args = parser.parse_args() work_dir = os.fspath(os.environ.get('PROJECT_WORK')) jfile = args.jsonfile dxf_file = args.dxf if args.jsonfile and args.dxf: jpath = os.path.join(work_dir, os.fspath(jfile)) dxf_path = os.path.join(work_dir, os.fspath(dxf_file)) if not os.path.exists(jpath): print("file %s does not exit", jpath) exit() if not os.path.exists(dxf_path): print("file %s does not exit", dxf_path) exit() basename = os.path.splitext(dxf_path)[0] timestamp = datetime.now().strftime(basename+"_%Y%m%d-%H%M%S.dxf") out_path = os.path.join(work_dir, timestamp) # erzeuge eine neue dxf Datei mit aktuellen Zeitstempel im Namen res_pos = new_dxf(jpath, dxf_path, out_path) else: parser.print_help()