production_pdf.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. # -*- coding: utf-8 -*-
  2. """订单生产图纸 PDF 生成(reportlab,参照工厂交付样式:刀版图 + 技术要求)。
  3. 两种产物:
  4. - production.pdf 生产图纸:图框 + 刀版展开图(矢量+尺寸标注)+ 技术要求块 + 设计预览图
  5. - vector.pdf 1:1 矢量刀版(mm 实尺,供 CorelDRAW/Illustrator 直接导入制版,
  6. 即传统 CDR 交付文件的行业标准替代——CorelDRAW X4+ 可直接打开 PDF)
  7. 中文使用 PDF 内置 CID 字体 STSong-Light,无需字体文件。
  8. """
  9. import os
  10. from datetime import datetime
  11. from reportlab.lib.colors import HexColor
  12. from reportlab.lib.units import mm
  13. from reportlab.pdfbase import pdfmetrics
  14. from reportlab.pdfbase.cidfonts import UnicodeCIDFont
  15. from reportlab.pdfgen import canvas as pdfcanvas
  16. from db import FILES_DIR
  17. PRODUCTION_NAME = "production.pdf"
  18. VECTOR_NAME = "vector.pdf"
  19. CUT_COLOR = HexColor("#c0392b") # 裁切线 红
  20. FOLD_COLOR = HexColor("#2c5f8a") # 折叠线 蓝
  21. BLEED_COLOR = HexColor("#c8a415") # 出血 黄
  22. DIM_COLOR = HexColor("#444444") # 尺寸标注
  23. INK = HexColor("#1a1a1a")
  24. if "STSong-Light" not in pdfmetrics.getRegisteredFontNames():
  25. pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))
  26. CN = "STSong-Light"
  27. def _order_folder(order_no):
  28. folder = os.path.join(FILES_DIR, order_no)
  29. os.makedirs(folder, exist_ok=True)
  30. return folder
  31. # ---------- 技术要求(按参考图纸措辞生成) ----------
  32. def tech_requirements(order) -> list:
  33. spec = order.get("spec") or {}
  34. if order["type"] == "box":
  35. w, d, h = spec.get("w"), spec.get("d"), spec.get("h")
  36. lines = [
  37. "技术要求:",
  38. "1、包装盒制造尺寸:%s×%s×%smm(内尺寸);结构:%s;" % (
  39. w, d, h, spec.get("boxName") or "-"),
  40. "2、纸张要求:%s;" % (spec.get("materialName") or "-"),
  41. "3、纸盒折弯处不得有开裂折皱现象;",
  42. "4、印刷要求:%s;字体清晰,不得有模糊现象;" % (
  43. (spec.get("printName") or "按设计稿") + (("(" + spec["printWay"] + ")") if spec.get("printWay") else "")),
  44. "5、生产数量:%s 件;" % spec.get("qty", "-"),
  45. "6、包装件应符合 GB/T 6543 及双方确认的打样标准要求。",
  46. ]
  47. else:
  48. # 印刷面尺寸:优先 spec 的 w/h,其次 sizeLabel,最后从刀版 faces 兜底
  49. if spec.get("w") and spec.get("h"):
  50. fw = "%s×%s" % (spec.get("w"), spec.get("h"))
  51. elif spec.get("sizeLabel"):
  52. fw = spec["sizeLabel"]
  53. else:
  54. faces = (order.get("dieline") or {}).get("faces") or []
  55. fw = "%.0f×%.0f" % (float(faces[0]["w"]), float(faces[0]["h"])) if faces else None
  56. unit = "" if (fw and "mm" in fw) else "mm"
  57. lines = [
  58. "技术要求:",
  59. "1、包装袋印刷面尺寸:%s%s;袋型:%s;" % (
  60. fw or "-", unit, spec.get("productName") or "-"),
  61. "2、材料要求:%s;工艺:%s;" % (
  62. spec.get("materialName") or "-", spec.get("finishName") or "-"),
  63. "3、印刷清晰,不得有模糊、偏色现象;出血 %smm;" % ((order.get("dieline") or {}).get("bleed", 3)),
  64. "4、生产数量:%s 只;" % spec.get("qty", "-"),
  65. "5、袋体应符合相关食品接触材料安全标准(如适用)。",
  66. ]
  67. return lines
  68. # ---------- 刀版几何绘制 ----------
  69. def _draw_box_dieline(c, dieline, ox, oy, scale, with_labels=True):
  70. """纸盒刀版:红实线轮廓 + 孔洞圆 + 蓝虚线折叠 + 面标签。"""
  71. panels = dieline.get("panels") or []
  72. folds = dieline.get("folds") or []
  73. face_names = {"front": "正面", "back": "背面", "left": "左", "right": "右",
  74. "top": "顶", "bottom": "底"}
  75. c.setLineWidth(0.6)
  76. c.setStrokeColor(CUT_COLOR)
  77. for p in panels:
  78. pts = p["poly"] if p.get("poly") else [
  79. (p["x"], p["y"]), (p["x"] + p["w"], p["y"]),
  80. (p["x"] + p["w"], p["y"] + p["h"]), (p["x"], p["y"] + p["h"]),
  81. ]
  82. if not pts:
  83. continue
  84. path = c.beginPath()
  85. path.moveTo((pts[0][0] + ox) * scale, (pts[0][1] + oy) * scale)
  86. for pt in pts[1:]:
  87. path.lineTo((pt[0] + ox) * scale, (pt[1] + oy) * scale)
  88. path.close()
  89. c.drawPath(path, stroke=1, fill=0)
  90. for hole in p.get("holes") or []:
  91. c.circle((hole["x"] + ox) * scale, (hole["y"] + oy) * scale,
  92. hole["r"] * scale, stroke=1, fill=0)
  93. if with_labels and p.get("face"):
  94. c.setFont(CN, max(6, 4 * scale))
  95. c.setFillColor(DIM_COLOR)
  96. c.drawCentredString((p["x"] + ox + p["w"] / 2) * scale,
  97. (p["y"] + oy + p["h"] / 2) * scale - 1.4,
  98. face_names.get(p["face"], p["face"]))
  99. c.setStrokeColor(FOLD_COLOR)
  100. c.setDash(4.5, 2.4)
  101. c.setLineWidth(1.0)
  102. for f in folds:
  103. c.line((f["x1"] + ox) * scale, (f["y1"] + oy) * scale,
  104. (f["x2"] + ox) * scale, (f["y2"] + oy) * scale)
  105. c.setDash()
  106. def _draw_bag_faces(c, dieline, ox, oy, scale, with_labels=True):
  107. """袋子印刷面轮廓:红实线印刷面 + 黄虚线出血 + 灰点线安全区。"""
  108. bleed = float(dieline.get("bleed") or 3)
  109. x = 0.0
  110. for face in dieline.get("faces") or []:
  111. w, h = float(face["w"]), float(face["h"])
  112. c.setLineWidth(0.6)
  113. c.setStrokeColor(CUT_COLOR)
  114. c.rect((x - 0 + ox) * scale, oy * scale, w * scale, h * scale, stroke=1, fill=0)
  115. c.setStrokeColor(BLEED_COLOR)
  116. c.setDash(4, 2.6)
  117. c.setLineWidth(0.5)
  118. c.rect((x - bleed + ox) * scale, (oy - bleed) * scale,
  119. (w + bleed * 2) * scale, (h + bleed * 2) * scale, stroke=1, fill=0)
  120. c.setStrokeColor(DIM_COLOR)
  121. c.setDash(1.2, 2)
  122. c.rect((x + bleed + ox) * scale, (oy + bleed) * scale,
  123. (w - bleed * 2) * scale, (h - bleed * 2) * scale, stroke=1, fill=0)
  124. c.setDash()
  125. if with_labels:
  126. c.setFont(CN, max(6, 4 * scale))
  127. c.setFillColor(DIM_COLOR)
  128. label = "正面" if face.get("key") == "front" else "背面" if face.get("key") == "back" else face.get("key", "")
  129. c.drawCentredString((x + ox + w / 2) * scale, (oy + h / 2) * scale - 1.4, label)
  130. x += w + 12 # 面间距 12mm
  131. def _dieline_extent(dieline):
  132. if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
  133. bleed = float(dieline.get("bleed") or 3)
  134. faces = dieline.get("faces") or []
  135. w = sum(float(f["w"]) for f in faces) + 12 * max(0, len(faces) - 1) + bleed * 2
  136. h = max((float(f["h"]) for f in faces), default=0) + bleed * 2
  137. return w, h
  138. size = dieline.get("size") or {"w": 0, "h": 0}
  139. return float(size.get("w", 0)), float(size.get("h", 0))
  140. def _draw_dim(c, x1, y1, x2, y2, offset, text, horizontal=True):
  141. """尺寸标注线(带箭头刻度与文字)。"""
  142. c.setStrokeColor(DIM_COLOR)
  143. c.setLineWidth(0.4)
  144. if horizontal:
  145. y = y1 + offset
  146. c.line(x1, y, x2, y)
  147. c.line(x1, y - 2, x1, y + 2)
  148. c.line(x2, y - 2, x2, y + 2)
  149. c.setFont(CN, 7)
  150. c.setFillColor(DIM_COLOR)
  151. c.drawCentredString((x1 + x2) / 2, y + 2, text)
  152. else:
  153. x = x1 + offset
  154. c.line(x, y1, x, y2)
  155. c.line(x - 2, y1, x + 2, y1)
  156. c.line(x - 2, y2, x + 2, y2)
  157. c.setFont(CN, 8.5)
  158. c.setFillColor(DIM_COLOR)
  159. c.saveState()
  160. c.translate(x - 3.5, (y1 + y2) / 2)
  161. c.rotate(90)
  162. c.drawCentredString(0, 0, text)
  163. c.restoreState()
  164. # ---------- 生产图纸 ----------
  165. def build_production_pdf(order, preview_paths=None) -> str:
  166. """A4 图纸:图框 + 刀版图 + 尺寸标注 + 技术要求 + 设计预览。"""
  167. dieline = order.get("dieline") or {}
  168. if not dieline:
  169. return None
  170. spec = order.get("spec") or {}
  171. content_w, content_h = _dieline_extent(dieline)
  172. # A4 竖版,图纸区偏横时自动横版
  173. a4_w, a4_h = 210 * mm, 297 * mm
  174. landscape = content_w > content_h * 1.4
  175. pw, ph = (a4_h, a4_w) if landscape else (a4_w, a4_h)
  176. path = os.path.join(_order_folder(order["orderNo"]), PRODUCTION_NAME)
  177. c = pdfcanvas.Canvas(path, pagesize=(pw, ph))
  178. # 图框
  179. margin = 12 * mm
  180. c.setLineWidth(1.2)
  181. c.setStrokeColor(INK)
  182. c.rect(margin, margin, pw - margin * 2, ph - margin * 2)
  183. # 标题
  184. title = "生产图纸 %s" % order["orderNo"]
  185. subtitle = ("包装盒" if order["type"] == "box" else "包装袋") + " · " + \
  186. (spec.get("boxName") or spec.get("productName") or "")
  187. c.setFont(CN, 15)
  188. c.setFillColor(INK)
  189. c.drawString(margin + 8 * mm, ph - margin - 11 * mm, title)
  190. c.setFont(CN, 9.5)
  191. c.setFillColor(DIM_COLOR)
  192. c.drawString(margin + 8 * mm, ph - margin - 17 * mm, subtitle + " · 出图日期 " + datetime.now().strftime("%Y-%m-%d"))
  193. # 刀版图区:内容四周预留 DIM_PAD 给尺寸标注,图形严格居中(保证标注与图例/图框不重叠)
  194. DIM_PAD = 12 # mm
  195. map_top = ph - margin - 24 * mm
  196. map_bottom = margin + 80 * mm # 下方留给图例与技术要求
  197. map_left = margin + 10 * mm
  198. map_right = pw - margin - 10 * mm
  199. avail_w = (map_right - map_left) / mm - DIM_PAD * 2
  200. avail_h = (map_top - map_bottom) / mm - DIM_PAD * 2
  201. scale = min(avail_w / max(content_w, 1), avail_h / max(content_h, 1), 4.0) * mm
  202. ox = -dieline.get("minX", 0)
  203. oy = -dieline.get("minY", 0)
  204. if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
  205. ox = 0
  206. oy = 0
  207. drawn_w = content_w * scale
  208. drawn_h = content_h * scale
  209. base_x = map_left + ((map_right - map_left) - drawn_w) / 2
  210. base_y = map_bottom + ((map_top - map_bottom) - drawn_h) / 2
  211. c.saveState()
  212. c.translate(base_x, base_y)
  213. if order["type"] == "box":
  214. _draw_box_dieline(c, dieline, ox, oy, scale)
  215. else:
  216. _draw_bag_faces(c, dieline, ox, oy, scale)
  217. # 总体尺寸标注(在 DIM_PAD 预留区内,与图例保持间隔)
  218. _draw_dim(c, 0, 0, drawn_w, 0, -8 * mm,
  219. "%.1f mm" % content_w, horizontal=True)
  220. _draw_dim(c, 0, 0, 0, drawn_h, -8 * mm,
  221. "%.1f mm" % content_h, horizontal=False)
  222. c.restoreState()
  223. # 图例(固定在绘图区下方,与尺寸标注至少隔开)
  224. lx = margin + 8 * mm
  225. ly = map_bottom - 9 * mm
  226. c.setLineWidth(0.9)
  227. c.setStrokeColor(CUT_COLOR)
  228. c.line(lx, ly, lx + 8 * mm, ly)
  229. c.setFont(CN, 7.5)
  230. c.setFillColor(INK)
  231. c.drawString(lx + 10 * mm, ly - 1, "裁切线")
  232. c.setStrokeColor(FOLD_COLOR)
  233. c.setDash(4, 2.6)
  234. c.line(lx + 30 * mm, ly, lx + 38 * mm, ly)
  235. c.setDash()
  236. c.drawString(lx + 40 * mm, ly - 1, "折叠线")
  237. c.setStrokeColor(BLEED_COLOR)
  238. c.setDash(4, 2.6)
  239. c.line(lx + 60 * mm, ly, lx + 68 * mm, ly)
  240. c.setDash()
  241. c.drawString(lx + 70 * mm, ly - 1, "出血线")
  242. # 技术要求块
  243. req = tech_requirements(order)
  244. ty = margin + 64 * mm
  245. c.setFont(CN, 9.5)
  246. c.setFillColor(INK)
  247. for line in req:
  248. c.drawString(margin + 8 * mm, ty, line)
  249. ty -= 5.6 * mm
  250. # 设计预览图(右下角)
  251. preview_paths = preview_paths or []
  252. imgs = [p for p in preview_paths if os.path.isfile(p)][:2]
  253. if imgs:
  254. from reportlab.lib.utils import ImageReader
  255. max_h = 44 * mm
  256. ix = pw - margin - 10 * mm
  257. for img_path in reversed(imgs):
  258. try:
  259. ir = ImageReader(img_path)
  260. iw, ih = ir.getSize()
  261. w = max_h * iw / ih
  262. ix -= w + 4 * mm
  263. except Exception:
  264. continue
  265. for img_path in imgs:
  266. try:
  267. ir = ImageReader(img_path)
  268. iw, ih = ir.getSize()
  269. w = max_h * iw / ih
  270. c.drawImage(ir, ix, margin + 66 * mm, w, max_h,
  271. preserveAspectRatio=True, mask='auto')
  272. ix += w + 4 * mm
  273. except Exception:
  274. pass
  275. # 页脚
  276. c.setFont(CN, 7)
  277. c.setFillColor(DIM_COLOR)
  278. c.drawCentredString(pw / 2, margin - 0.5 * mm + 3 * mm,
  279. "POUCHLAB 袋研社 · 本图纸与订单 %s 一一对应,改版需重新出图" % order["orderNo"])
  280. c.showPage()
  281. c.save()
  282. return path
  283. # ---------- 1:1 矢量刀版(CDR/AI 兼容) ----------
  284. def build_vector_pdf(order) -> str:
  285. """mm 实尺单页矢量刀版,CorelDRAW/Illustrator 可直接打开编辑(替代 CDR 交付)。"""
  286. dieline = order.get("dieline") or {}
  287. if not dieline:
  288. return None
  289. content_w, content_h = _dieline_extent(dieline)
  290. pad = 10
  291. pw, ph = (content_w + pad * 2) * mm, (content_h + pad * 2) * mm
  292. path = os.path.join(_order_folder(order["orderNo"]), VECTOR_NAME)
  293. c = pdfcanvas.Canvas(path, pagesize=(pw, ph))
  294. c.setTitle("%s dieline 1:1" % order["orderNo"])
  295. ox = -dieline.get("minX", 0)
  296. oy = -dieline.get("minY", 0)
  297. if dieline.get("kind") == "bag" or (dieline.get("faces") and not dieline.get("panels")):
  298. ox, oy = 0, 0
  299. c.saveState()
  300. c.translate(pad * mm, pad * mm)
  301. if order["type"] == "box":
  302. _draw_box_dieline(c, dieline, ox, oy, mm, with_labels=False)
  303. else:
  304. _draw_bag_faces(c, dieline, ox, oy, mm, with_labels=False)
  305. c.restoreState()
  306. # 角落标记(1:1 校验尺寸 + 订单号)
  307. c.setFont(CN, 7)
  308. c.setFillColor(DIM_COLOR)
  309. c.drawString(4 * mm, ph - 8 * mm, "%s · 1:1 (mm) · CUT cut / FOLD fold(dashed)" % order["orderNo"])
  310. c.showPage()
  311. c.save()
  312. return path
  313. def production_pdf_path(order, preview_paths=None) -> str:
  314. path = os.path.join(_order_folder(order["orderNo"]), PRODUCTION_NAME)
  315. cached = path + "." + str(order["updatedAt"]) + ".ok"
  316. if os.path.exists(path) and os.path.exists(cached):
  317. return path
  318. result = build_production_pdf(order, preview_paths)
  319. if result:
  320. folder = os.path.dirname(path)
  321. prefix = PRODUCTION_NAME + "."
  322. for stale in os.listdir(folder):
  323. if stale.startswith(prefix) and stale.endswith(".ok"):
  324. try:
  325. os.remove(os.path.join(folder, stale))
  326. except OSError:
  327. pass
  328. with open(cached, "w") as f:
  329. f.write("ok")
  330. return result
  331. def vector_pdf_path(order) -> str:
  332. path = os.path.join(_order_folder(order["orderNo"]), VECTOR_NAME)
  333. cached = path + "." + str(order["updatedAt"]) + ".ok"
  334. if os.path.exists(path) and os.path.exists(cached):
  335. return path
  336. result = build_vector_pdf(order)
  337. if result:
  338. folder = os.path.dirname(path)
  339. prefix = VECTOR_NAME + "."
  340. for stale in os.listdir(folder):
  341. if stale.startswith(prefix) and stale.endswith(".ok"):
  342. try:
  343. os.remove(os.path.join(folder, stale))
  344. except OSError:
  345. pass
  346. with open(cached, "w") as f:
  347. f.write("ok")
  348. return result