# -*- coding: utf-8 -*- """工厂 CAD 图纸生成(ezdxf,DXF R2010,单位 mm、1:1)。 - 纸盒订单:用前端提交的刀版几何(panels / folds / holes)绘制完整展开刀版图 图层 CUT 裁切线(红) / FOLD 折叠线(蓝虚线) / DIM 尺寸标注 / INFO 标题栏 - 袋子订单:袋体系预制袋体,图纸为印刷面轮廓图(正面/背面 + 3mm 出血 + 安全区) 图纸文字统一使用 ASCII(避免部分 CAD 查看器缺少中文字体出现乱码), 中文说明由后台管理页面展示。 """ import io import os from datetime import datetime import ezdxf from ezdxf.enums import TextEntityAlignment from db import FILES_DIR, db OUTPUT_NAME = "cad.dxf" PREVIEW_NAME = "cad-preview.svg" def ascii_safe(value) -> str: """DXF 文本保持纯 ASCII(部分 CAD/激光切割软件对非 ASCII 显示乱码)。 中文名无法转写时回退占位符,中文说明由后台管理页展示。""" s = str(value or "").strip() cleaned = "".join(ch if ord(ch) < 128 else "" for ch in s).strip(" -()") return cleaned or "-" def _new_doc(): doc = ezdxf.new("R2010", setup=True) doc.header["$INSUNITS"] = 4 # 4 = mm doc.header["$MEASUREMENT"] = 1 # metric doc.header["$LUNITS"] = 2 doc.header["$DIMDEC"] = 1 msp = doc.modelspace() layers = [ ("CUT", 1, "CONTINUOUS"), # 裁切线 红 ("FOLD", 5, "DASHED"), # 折叠线 蓝 虚线 ("BLEED", 2, "DASHED"), # 出血 黄 虚线 ("SAFE", 8, "DOT"), # 安全区 灰 点线 ("DIM", 8, "CONTINUOUS"), # 尺寸标注 ("INFO", 7, "CONTINUOUS"), # 图框/标题栏 ] for name, color, lt in layers: doc.layers.add(name, color=color, linetype=lt) return doc, msp def _polyline(msp, points, layer, closed=True): msp.add_lwpolyline( [(round(p[0], 3), round(p[1], 3)) for p in points], close=closed, dxfattribs={"layer": layer}, ) def _rect(msp, x, y, w, h, layer): _polyline(msp, [(x, y), (x + w, y), (x + w, y + h), (x, y + h)], layer) def _dim(msp, p1, p2, offset, text): """线性尺寸标注(p1->p2 水平或垂直)。""" dim = msp.add_linear_dim( base=(round((p1[0] + p2[0]) / 2, 3), round((p1[1] + p2[1]) / 2 + offset, 3)), p1=(round(p1[0], 3), round(p1[1], 3)), p2=(round(p2[0], 3), round(p2[1], 3)), dimstyle="EZDXF", text=text, dxfattribs={"layer": "DIM"}, ) dim.render() def _title_block(msp, origin_x, origin_y, rows): """图框标题栏:绘制在图纸下方,宽 150mm。""" w, row_h = 150.0, 6.0 _rect(msp, origin_x, origin_y, w, row_h * len(rows) + 2, "INFO") for i, (label, value) in enumerate(rows): y = origin_y + row_h * (len(rows) - 1 - i) + 1 cell_split = origin_x + 42 if i < len(rows) - 1: # 行间分隔线 msp.add_line((origin_x, y), (origin_x + w, y), dxfattribs={"layer": "INFO"}) msp.add_line( (cell_split, y), (cell_split, y + row_h), dxfattribs={"layer": "INFO"} ) t1 = msp.add_text( label, height=2.6, dxfattribs={"layer": "INFO", "style": "OpenSans"} ) t1.set_placement((origin_x + 2, y + 1.6), align=TextEntityAlignment.LEFT) t2 = msp.add_text( value, height=2.6, dxfattribs={"layer": "INFO", "style": "OpenSans"} ) t2.set_placement((cell_split + 2, y + 1.6), align=TextEntityAlignment.LEFT) def build_box_dxf(dieline: dict, order_no: str) -> "ezdxf.document.Drawing": doc, msp = _new_doc() meta = dieline.get("meta") or {} panels = dieline.get("panels") or [] folds = dieline.get("folds") or [] size = dieline.get("size") or {"w": 0, "h": 0} min_x = dieline.get("minX", 0) min_y = dieline.get("minY", 0) ox, oy = -min_x, -min_y # 原点归一化到 (0,0) for p in panels: if p.get("poly"): pts = [(pt[0] + ox, pt[1] + oy) for pt in p["poly"]] _polyline(msp, pts, "CUT") else: _rect(msp, p["x"] + ox, p["y"] + oy, p["w"], p["h"], "CUT") for hole in p.get("holes") or []: msp.add_circle( (hole["x"] + ox, hole["y"] + oy), hole["r"], dxfattribs={"layer": "CUT"}, ) # 面标签(可印刷面;poly 面也已预算好外接框 x/y/w/h) if p.get("face"): cx = p["x"] + ox + p["w"] / 2 cy = p["y"] + oy + p["h"] / 2 label = {"front": "FRONT", "back": "BACK", "left": "LEFT", "right": "RIGHT", "top": "TOP", "bottom": "BOTTOM"}.get(p["face"], p["face"].upper()) t = msp.add_text(label, height=4, dxfattribs={"layer": "INFO", "style": "OpenSans"}) t.set_placement((round(cx, 2), round(cy, 2)), align=TextEntityAlignment.MIDDLE_CENTER) for f in folds: msp.add_line( (round(f["x1"] + ox, 3), round(f["y1"] + oy, 3)), (round(f["x2"] + ox, 3), round(f["y2"] + oy, 3)), dxfattribs={"layer": "FOLD"}, ) # 总体尺寸标注 W, H = size.get("w", 0), size.get("h", 0) if W > 0: _dim(msp, (0, 0), (W, 0), -8, "%.1f" % W) if H > 0: _dim(msp, (0, 0), (0, H), -8, "%.1f" % H) inner = meta.get("inner") or {} rows = [ ("POUCHLAB DIELINE / FACTORY DRAWING", ""), ("ORDER NO", order_no), ("BOX TYPE / NO", "%s (%s)" % (ascii_safe(meta.get("boxName")), meta.get("boxNo") or "-")), ("INNER SIZE (LxWxH)", "%s x %s x %s mm" % (inner.get("w"), inner.get("d"), inner.get("h"))), ("UNFOLDED SIZE", "%.1f x %.1f mm" % (W, H)), ("MATERIAL (t=mm)", "%s (t=%s)" % (ascii_safe(meta.get("material")), meta.get("thickness") or "-")), ("QTY", str(meta.get("qty") or "-")), ("DATE", datetime.now().strftime("%Y-%m-%d")), ("UNIT & SCALE", "mm 1:1 CUT=cut FOLD=fold(dashed)"), ] _title_block(msp, 0, -46, rows) doc.header["$EXTMIN"] = (-12.0, -46.0 - row_h_stub(len(rows)) - 4, 0) doc.header["$EXTMAX"] = (W + 12, H + 12, 0) return doc def row_h_stub(n): return 6.0 * n def build_bag_dxf(dieline: dict, order_no: str) -> "ezdxf.document.Drawing": doc, msp = _new_doc() meta = dieline.get("meta") or {} faces = dieline.get("faces") or [] bleed = float(dieline.get("bleed") or 3) gap = 12.0 x = 0.0 max_h = 0.0 for face in faces: w, h = float(face["w"]), float(face["h"]) label = str(face.get("key") or "").upper() _rect(msp, x, 0, w, h, "CUT") _rect(msp, x - bleed, -bleed, w + bleed * 2, h + bleed * 2, "BLEED") _rect(msp, x + bleed, bleed, w - bleed * 2, h - bleed * 2, "SAFE") _dim(msp, (x, 0), (x + w, 0), -bleed - 8, "%.1f" % w) _dim(msp, (x, 0), (x, h), -bleed - 8, "%.1f" % h) t = msp.add_text(label, height=4, dxfattribs={"layer": "INFO", "style": "OpenSans"}) t.set_placement((round(x + w / 2, 2), round(h / 2, 2)), align=TextEntityAlignment.MIDDLE_CENTER) x += w + gap max_h = max(max_h, h) rows = [ ("POUCHLAB PRINT LAYOUT / FACTORY DRAWING", ""), ("ORDER NO", order_no), ("PRODUCT", "%s" % ascii_safe(meta.get("productName"))), ("FACE SIZE", " / ".join( "%.1f x %.1f mm" % (float(f["w"]), float(f["h"])) for f in faces)), ("MATERIAL", ascii_safe(meta.get("material"))), ("FINISH", ascii_safe(meta.get("finish"))), ("QTY", str(meta.get("qty") or "-")), ("DATE", datetime.now().strftime("%Y-%m-%d")), ("UNIT & SCALE", "mm 1:1 CUT=face BLEED=%gmm SAFE=inner" % bleed), ] _title_block(msp, 0, -bleed - 18, rows) doc.header["$EXTMIN"] = (-bleed - 12.0, -bleed - 18 - row_h_stub(len(rows)) - 6, 0) doc.header["$EXTMAX"] = (x + bleed + 12, max_h + bleed + 12, 0) return doc def order_dxf_path(order_id: int) -> str: with db() as cur: cur.execute("SELECT order_no FROM orders WHERE id = %s", (order_id,)) row = cur.fetchone() if not row: return None folder = os.path.join(FILES_DIR, row["order_no"]) os.makedirs(folder, exist_ok=True) return os.path.join(folder, OUTPUT_NAME) def render_preview_svg(doc, preview_path: str): """DXF → 预览 SVG(与 QuotePilot/rag 的 CAD Worker 同款方式): ezdxf drawing add-on SVGBackend 渲染,白底 + 深色线条,A3 横版自适应。""" import re as _re from ezdxf.addons.drawing import Frontend, RenderContext from ezdxf.addons.drawing.layout import Page from ezdxf.addons.drawing.svg import SVGBackend backend = SVGBackend() backend.set_background("#FFFFFF") ctx = RenderContext(doc) frontend = Frontend(ctx, backend) frontend.draw_layout(doc.modelspace(), finalize=True) svg_text = backend.get_string(Page(420, 297)) # SVG 后端默认深色画布/白色线条,重着色为打印友好:白底 + #1F2937 深灰线条 svg_text = _re.sub(r'( str: """为订单生成(或命中缓存)DXF 文件与预览 SVG,返回 DXF 绝对路径。缓存以 updated_at 失效。""" path = order_dxf_path(order["id"]) if not path: return None preview_path = os.path.join(os.path.dirname(path), PREVIEW_NAME) cached = path + "." + str(order["updatedAt"]) + ".ok" if os.path.exists(path) and os.path.exists(cached) and os.path.exists(preview_path): return path dieline = order.get("dieline") or {} if order["type"] == "box": doc = build_box_dxf(dieline, order["orderNo"]) else: doc = build_bag_dxf(dieline, order["orderNo"]) buf = io.StringIO() doc.write(buf, fmt="ascii") with open(path, "w", encoding="ascii") as f: f.write(buf.getvalue()) try: render_preview_svg(doc, preview_path) except Exception: # 预览失败不影响 DXF 生成(旧缓存订单补预览时 DXF 已存在) if not os.path.exists(preview_path): try: os.remove(preview_path) except OSError: pass for stale in os.listdir(os.path.dirname(path)): if stale.endswith(".ok"): try: os.remove(os.path.join(os.path.dirname(path), stale)) except OSError: pass with open(cached, "w") as f: f.write("ok") return path def preview_svg_path(order: dict) -> str: """确保预览已生成并返回其绝对路径;无法生成时返回 None。""" generate(order) path = os.path.join( os.path.dirname(order_dxf_path(order["id"])), PREVIEW_NAME ) return path if os.path.isfile(path) else None