| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395 |
- # -*- coding: utf-8 -*-
- """订单生产图纸 PDF 生成(reportlab,参照工厂交付样式:刀版图 + 技术要求)。
- 两种产物:
- - production.pdf 生产图纸:图框 + 刀版展开图(矢量+尺寸标注)+ 技术要求块 + 设计预览图
- - vector.pdf 1:1 矢量刀版(mm 实尺,供 CorelDRAW/Illustrator 直接导入制版,
- 即传统 CDR 交付文件的行业标准替代——CorelDRAW X4+ 可直接打开 PDF)
- 中文使用 PDF 内置 CID 字体 STSong-Light,无需字体文件。
- """
- import os
- from datetime import datetime
- from reportlab.lib.colors import HexColor
- from reportlab.lib.units import mm
- from reportlab.pdfbase import pdfmetrics
- from reportlab.pdfbase.cidfonts import UnicodeCIDFont
- from reportlab.pdfgen import canvas as pdfcanvas
- from db import FILES_DIR
- PRODUCTION_NAME = "production.pdf"
- VECTOR_NAME = "vector.pdf"
- CUT_COLOR = HexColor("#c0392b") # 裁切线 红
- FOLD_COLOR = HexColor("#2c5f8a") # 折叠线 蓝
- BLEED_COLOR = HexColor("#c8a415") # 出血 黄
- DIM_COLOR = HexColor("#444444") # 尺寸标注
- INK = HexColor("#1a1a1a")
- if "STSong-Light" not in pdfmetrics.getRegisteredFontNames():
- pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))
- CN = "STSong-Light"
- def _order_folder(order_no):
- folder = os.path.join(FILES_DIR, order_no)
- os.makedirs(folder, exist_ok=True)
- return folder
- # ---------- 技术要求(按参考图纸措辞生成) ----------
- def tech_requirements(order) -> list:
- spec = order.get("spec") or {}
- if order["type"] == "box":
- w, d, h = spec.get("w"), spec.get("d"), spec.get("h")
- lines = [
- "技术要求:",
- "1、包装盒制造尺寸:%s×%s×%smm(内尺寸);结构:%s;" % (
- w, d, h, spec.get("boxName") or "-"),
- "2、纸张要求:%s;" % (spec.get("materialName") or "-"),
- "3、纸盒折弯处不得有开裂折皱现象;",
- "4、印刷要求:%s;字体清晰,不得有模糊现象;" % (
- (spec.get("printName") or "按设计稿") + (("(" + spec["printWay"] + ")") if spec.get("printWay") else "")),
- "5、生产数量:%s 件;" % spec.get("qty", "-"),
- "6、包装件应符合 GB/T 6543 及双方确认的打样标准要求。",
- ]
- else:
- # 印刷面尺寸:优先 spec 的 w/h,其次 sizeLabel,最后从刀版 faces 兜底
- if spec.get("w") and spec.get("h"):
- fw = "%s×%s" % (spec.get("w"), spec.get("h"))
- elif spec.get("sizeLabel"):
- fw = spec["sizeLabel"]
- else:
- faces = (order.get("dieline") or {}).get("faces") or []
- fw = "%.0f×%.0f" % (float(faces[0]["w"]), float(faces[0]["h"])) if faces else None
- unit = "" if (fw and "mm" in fw) else "mm"
- lines = [
- "技术要求:",
- "1、包装袋印刷面尺寸:%s%s;袋型:%s;" % (
- fw or "-", unit, spec.get("productName") or "-"),
- "2、材料要求:%s;工艺:%s;" % (
- spec.get("materialName") or "-", spec.get("finishName") or "-"),
- "3、印刷清晰,不得有模糊、偏色现象;出血 %smm;" % ((order.get("dieline") or {}).get("bleed", 3)),
- "4、生产数量:%s 只;" % spec.get("qty", "-"),
- "5、袋体应符合相关食品接触材料安全标准(如适用)。",
- ]
- return lines
- # ---------- 刀版几何绘制 ----------
- def _draw_box_dieline(c, dieline, ox, oy, scale, with_labels=True):
- """纸盒刀版:红实线轮廓 + 孔洞圆 + 蓝虚线折叠 + 面标签。"""
- panels = dieline.get("panels") or []
- folds = dieline.get("folds") or []
- face_names = {"front": "正面", "back": "背面", "left": "左", "right": "右",
- "top": "顶", "bottom": "底"}
- c.setLineWidth(0.6)
- c.setStrokeColor(CUT_COLOR)
- for p in panels:
- pts = p["poly"] if p.get("poly") else [
- (p["x"], p["y"]), (p["x"] + p["w"], p["y"]),
- (p["x"] + p["w"], p["y"] + p["h"]), (p["x"], p["y"] + p["h"]),
- ]
- if not pts:
- continue
- path = c.beginPath()
- path.moveTo((pts[0][0] + ox) * scale, (pts[0][1] + oy) * scale)
- for pt in pts[1:]:
- path.lineTo((pt[0] + ox) * scale, (pt[1] + oy) * scale)
- path.close()
- c.drawPath(path, stroke=1, fill=0)
- for hole in p.get("holes") or []:
- c.circle((hole["x"] + ox) * scale, (hole["y"] + oy) * scale,
- hole["r"] * scale, stroke=1, fill=0)
- if with_labels and p.get("face"):
- c.setFont(CN, max(6, 4 * scale))
- c.setFillColor(DIM_COLOR)
- c.drawCentredString((p["x"] + ox + p["w"] / 2) * scale,
- (p["y"] + oy + p["h"] / 2) * scale - 1.4,
- face_names.get(p["face"], p["face"]))
- c.setStrokeColor(FOLD_COLOR)
- c.setDash(4.5, 2.4)
- c.setLineWidth(1.0)
- for f in folds:
- c.line((f["x1"] + ox) * scale, (f["y1"] + oy) * scale,
- (f["x2"] + ox) * scale, (f["y2"] + oy) * scale)
- c.setDash()
- def _draw_bag_faces(c, dieline, ox, oy, scale, with_labels=True):
- """袋子印刷面轮廓:红实线印刷面 + 黄虚线出血 + 灰点线安全区。"""
- bleed = float(dieline.get("bleed") or 3)
- x = 0.0
- for face in dieline.get("faces") or []:
- w, h = float(face["w"]), float(face["h"])
- c.setLineWidth(0.6)
- c.setStrokeColor(CUT_COLOR)
- c.rect((x - 0 + ox) * scale, oy * scale, w * scale, h * scale, stroke=1, fill=0)
- c.setStrokeColor(BLEED_COLOR)
- c.setDash(4, 2.6)
- c.setLineWidth(0.5)
- c.rect((x - bleed + ox) * scale, (oy - bleed) * scale,
- (w + bleed * 2) * scale, (h + bleed * 2) * scale, stroke=1, fill=0)
- c.setStrokeColor(DIM_COLOR)
- c.setDash(1.2, 2)
- c.rect((x + bleed + ox) * scale, (oy + bleed) * scale,
- (w - bleed * 2) * scale, (h - bleed * 2) * scale, stroke=1, fill=0)
- c.setDash()
- if with_labels:
- c.setFont(CN, max(6, 4 * scale))
- c.setFillColor(DIM_COLOR)
- label = "正面" if face.get("key") == "front" else "背面" if face.get("key") == "back" else face.get("key", "")
- c.drawCentredString((x + ox + w / 2) * scale, (oy + h / 2) * scale - 1.4, label)
- x += w + 12 # 面间距 12mm
- def _dieline_extent(dieline):
- if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
- bleed = float(dieline.get("bleed") or 3)
- faces = dieline.get("faces") or []
- w = sum(float(f["w"]) for f in faces) + 12 * max(0, len(faces) - 1) + bleed * 2
- h = max((float(f["h"]) for f in faces), default=0) + bleed * 2
- return w, h
- size = dieline.get("size") or {"w": 0, "h": 0}
- return float(size.get("w", 0)), float(size.get("h", 0))
- def _draw_dim(c, x1, y1, x2, y2, offset, text, horizontal=True):
- """尺寸标注线(带箭头刻度与文字)。"""
- c.setStrokeColor(DIM_COLOR)
- c.setLineWidth(0.4)
- if horizontal:
- y = y1 + offset
- c.line(x1, y, x2, y)
- c.line(x1, y - 2, x1, y + 2)
- c.line(x2, y - 2, x2, y + 2)
- c.setFont(CN, 7)
- c.setFillColor(DIM_COLOR)
- c.drawCentredString((x1 + x2) / 2, y + 2, text)
- else:
- x = x1 + offset
- c.line(x, y1, x, y2)
- c.line(x - 2, y1, x + 2, y1)
- c.line(x - 2, y2, x + 2, y2)
- c.setFont(CN, 8.5)
- c.setFillColor(DIM_COLOR)
- c.saveState()
- c.translate(x - 3.5, (y1 + y2) / 2)
- c.rotate(90)
- c.drawCentredString(0, 0, text)
- c.restoreState()
- # ---------- 生产图纸 ----------
- def build_production_pdf(order, preview_paths=None) -> str:
- """A4 图纸:图框 + 刀版图 + 尺寸标注 + 技术要求 + 设计预览。"""
- dieline = order.get("dieline") or {}
- if not dieline:
- return None
- spec = order.get("spec") or {}
- content_w, content_h = _dieline_extent(dieline)
- # A4 竖版,图纸区偏横时自动横版
- a4_w, a4_h = 210 * mm, 297 * mm
- landscape = content_w > content_h * 1.4
- pw, ph = (a4_h, a4_w) if landscape else (a4_w, a4_h)
- path = os.path.join(_order_folder(order["orderNo"]), PRODUCTION_NAME)
- c = pdfcanvas.Canvas(path, pagesize=(pw, ph))
- # 图框
- margin = 12 * mm
- c.setLineWidth(1.2)
- c.setStrokeColor(INK)
- c.rect(margin, margin, pw - margin * 2, ph - margin * 2)
- # 标题
- title = "生产图纸 %s" % order["orderNo"]
- subtitle = ("包装盒" if order["type"] == "box" else "包装袋") + " · " + \
- (spec.get("boxName") or spec.get("productName") or "")
- c.setFont(CN, 15)
- c.setFillColor(INK)
- c.drawString(margin + 8 * mm, ph - margin - 11 * mm, title)
- c.setFont(CN, 9.5)
- c.setFillColor(DIM_COLOR)
- c.drawString(margin + 8 * mm, ph - margin - 17 * mm, subtitle + " · 出图日期 " + datetime.now().strftime("%Y-%m-%d"))
- # 刀版图区:内容四周预留 DIM_PAD 给尺寸标注,图形严格居中(保证标注与图例/图框不重叠)
- DIM_PAD = 12 # mm
- map_top = ph - margin - 24 * mm
- map_bottom = margin + 80 * mm # 下方留给图例与技术要求
- map_left = margin + 10 * mm
- map_right = pw - margin - 10 * mm
- avail_w = (map_right - map_left) / mm - DIM_PAD * 2
- avail_h = (map_top - map_bottom) / mm - DIM_PAD * 2
- scale = min(avail_w / max(content_w, 1), avail_h / max(content_h, 1), 4.0) * mm
- ox = -dieline.get("minX", 0)
- oy = -dieline.get("minY", 0)
- if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
- ox = 0
- oy = 0
- drawn_w = content_w * scale
- drawn_h = content_h * scale
- base_x = map_left + ((map_right - map_left) - drawn_w) / 2
- base_y = map_bottom + ((map_top - map_bottom) - drawn_h) / 2
- c.saveState()
- c.translate(base_x, base_y)
- if order["type"] == "box":
- _draw_box_dieline(c, dieline, ox, oy, scale)
- else:
- _draw_bag_faces(c, dieline, ox, oy, scale)
- # 总体尺寸标注(在 DIM_PAD 预留区内,与图例保持间隔)
- _draw_dim(c, 0, 0, drawn_w, 0, -8 * mm,
- "%.1f mm" % content_w, horizontal=True)
- _draw_dim(c, 0, 0, 0, drawn_h, -8 * mm,
- "%.1f mm" % content_h, horizontal=False)
- c.restoreState()
- # 图例(固定在绘图区下方,与尺寸标注至少隔开)
- lx = margin + 8 * mm
- ly = map_bottom - 9 * mm
- c.setLineWidth(0.9)
- c.setStrokeColor(CUT_COLOR)
- c.line(lx, ly, lx + 8 * mm, ly)
- c.setFont(CN, 7.5)
- c.setFillColor(INK)
- c.drawString(lx + 10 * mm, ly - 1, "裁切线")
- c.setStrokeColor(FOLD_COLOR)
- c.setDash(4, 2.6)
- c.line(lx + 30 * mm, ly, lx + 38 * mm, ly)
- c.setDash()
- c.drawString(lx + 40 * mm, ly - 1, "折叠线")
- c.setStrokeColor(BLEED_COLOR)
- c.setDash(4, 2.6)
- c.line(lx + 60 * mm, ly, lx + 68 * mm, ly)
- c.setDash()
- c.drawString(lx + 70 * mm, ly - 1, "出血线")
- # 技术要求块
- req = tech_requirements(order)
- ty = margin + 64 * mm
- c.setFont(CN, 9.5)
- c.setFillColor(INK)
- for line in req:
- c.drawString(margin + 8 * mm, ty, line)
- ty -= 5.6 * mm
- # 设计预览图(右下角)
- preview_paths = preview_paths or []
- imgs = [p for p in preview_paths if os.path.isfile(p)][:2]
- if imgs:
- from reportlab.lib.utils import ImageReader
- max_h = 44 * mm
- ix = pw - margin - 10 * mm
- for img_path in reversed(imgs):
- try:
- ir = ImageReader(img_path)
- iw, ih = ir.getSize()
- w = max_h * iw / ih
- ix -= w + 4 * mm
- except Exception:
- continue
- for img_path in imgs:
- try:
- ir = ImageReader(img_path)
- iw, ih = ir.getSize()
- w = max_h * iw / ih
- c.drawImage(ir, ix, margin + 66 * mm, w, max_h,
- preserveAspectRatio=True, mask='auto')
- ix += w + 4 * mm
- except Exception:
- pass
- # 页脚
- c.setFont(CN, 7)
- c.setFillColor(DIM_COLOR)
- c.drawCentredString(pw / 2, margin - 0.5 * mm + 3 * mm,
- "Steady Packaging · 本图纸与订单 %s 一一对应,改版需重新出图" % order["orderNo"])
- c.showPage()
- c.save()
- return path
- # ---------- 1:1 矢量刀版(CDR/AI 兼容) ----------
- def build_vector_pdf(order) -> str:
- """mm 实尺单页矢量刀版,CorelDRAW/Illustrator 可直接打开编辑(替代 CDR 交付)。"""
- dieline = order.get("dieline") or {}
- if not dieline:
- return None
- content_w, content_h = _dieline_extent(dieline)
- pad = 10
- pw, ph = (content_w + pad * 2) * mm, (content_h + pad * 2) * mm
- path = os.path.join(_order_folder(order["orderNo"]), VECTOR_NAME)
- c = pdfcanvas.Canvas(path, pagesize=(pw, ph))
- c.setTitle("%s dieline 1:1" % order["orderNo"])
- ox = -dieline.get("minX", 0)
- oy = -dieline.get("minY", 0)
- if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
- ox, oy = 0, 0
- c.saveState()
- c.translate(pad * mm, pad * mm)
- if order["type"] == "box":
- _draw_box_dieline(c, dieline, ox, oy, mm, with_labels=False)
- else:
- _draw_bag_faces(c, dieline, ox, oy, mm, with_labels=False)
- c.restoreState()
- # 角落标记(1:1 校验尺寸 + 订单号)
- c.setFont(CN, 7)
- c.setFillColor(DIM_COLOR)
- c.drawString(4 * mm, ph - 8 * mm, "%s · 1:1 (mm) · CUT cut / FOLD fold(dashed)" % order["orderNo"])
- c.showPage()
- c.save()
- return path
- def production_pdf_path(order, preview_paths=None) -> str:
- path = os.path.join(_order_folder(order["orderNo"]), PRODUCTION_NAME)
- cached = path + "." + str(order["updatedAt"]) + ".ok"
- if os.path.exists(path) and os.path.exists(cached):
- return path
- result = build_production_pdf(order, preview_paths)
- if result:
- folder = os.path.dirname(path)
- prefix = PRODUCTION_NAME + "."
- for stale in os.listdir(folder):
- if stale.startswith(prefix) and stale.endswith(".ok"):
- try:
- os.remove(os.path.join(folder, stale))
- except OSError:
- pass
- with open(cached, "w") as f:
- f.write("ok")
- return result
- def vector_pdf_path(order) -> str:
- path = os.path.join(_order_folder(order["orderNo"]), VECTOR_NAME)
- cached = path + "." + str(order["updatedAt"]) + ".ok"
- if os.path.exists(path) and os.path.exists(cached):
- return path
- result = build_vector_pdf(order)
- if result:
- folder = os.path.dirname(path)
- prefix = VECTOR_NAME + "."
- for stale in os.listdir(folder):
- if stale.startswith(prefix) and stale.endswith(".ok"):
- try:
- os.remove(os.path.join(folder, stale))
- except OSError:
- pass
- with open(cached, "w") as f:
- f.write("ok")
- return result
|