苏州元墨互联技术有限公司
← 返回首页
无损线稿 轻量PDF 纸盒模切线 纸盒材料 纸盒设备
轻量PDF
📷
轻量PDF | 快速生成
规格自定义 · 高清导出 · 可商用
标准格式 · 快速生成 · 可直接打印
后端完整 Python 代码(和前端解析规则完全匹配,直接新建 py 文件运行) python 运行 from flask import Flask, request, make_response from io import BytesIO from reportlab.pdfgen import canvas import re import time app = Flask(__name__) # 全局跨域 @app.after_request def after_request(response): response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS" response.headers["Access-Control-Allow-Headers"] = "Content-Type" return response # 防爬域名校验 @app.before_request def anti_crawl(): ua = request.headers.get("User-Agent", "").lower() bad_ua = ["scrapy", "requests"] if any(x in ua for x in bad_ua): return "解析失败:访问受限", 403 ref = request.headers.get("Referer", "") if ref and "wm-pro.top" not in ref: return "解析失败:无权限", 403 if request.host not in ("www.wm-pro.top", "wm-pro.top", "127.0.0.1", "localhost"): return "解析失败:非法域名", 403 # 单位换算规则 和前端完全统一 UNIT_RULE = { "mm": 1, "MM": 1, "毫米": 1, "cm": 10, "CM": 10, "厘米": 10, "m": 1000, "M": 1000, "米": 1000, "in": 25.4, "IN": 25.4, "inch": 25.4, "Inch": 25.4, "英寸": 25.4, '"': 25.4 } MM_TO_PX = 2.834995 # 解析单段尺寸(支持单边独立单位) def extract_num_and_unit(s): s = s.strip() num_match = re.search(r"\d+\.?\d*", s) if not num_match: return None, None num = float(num_match.group()) if num <= 0: return None, None unit_rate = None lower_s = s.lower() for unit, rate in UNIT_RULE.items(): if unit in s or unit in lower_s: unit_rate = rate break if unit_rate is None and '"' in s: unit_rate = 25.4 if unit_rate is None: return None, None mm_val = round(num * unit_rate, 2) px = round(mm_val * MM_TO_PX, 4) return mm_val, px # 整体清洗拆分长宽 def parse_size_text(text): clean = re.sub(r"\s+", "", text) clean = re.sub(r"[xX×]", "*", clean) parts = clean.split("*") if len(parts) != 2: return 0, 0 w_mm, w_px = extract_num_and_unit(parts[0]) h_mm, h_px = extract_num_and_unit(parts[1]) if w_mm is None or h_mm is None: return 0, 0 return w_px, h_px # PDF生成接口 @app.route("/light_pdf", methods=["POST", "OPTIONS"]) def light_pdf(): if request.method == "OPTIONS": return "", 200 try: raw_input = request.form.get("sizeText", "").strip() if not raw_input: return "解析失败:尺寸不能为空", 400 w_px, h_px = parse_size_text(raw_input) if w_px <= 0 or h_px <= 0: return "解析失败:尺寸缺失单位或格式错误", 400 buf = BytesIO() c = canvas.Canvas(buf, pagesize=(w_px, h_px)) c.setFillColor("white") c.rect(0, 0, w_px, fill=1) c.setFillColor("white") c.setFont("Helvetica", 1) c.drawString(5, 5, "wm-pro-" + str(int(time.time()))) c.save() buf.seek(0) resp = make_response(buf.read()) resp.headers["Content-Type"] = "application/pdf" resp.headers["Content-Disposition"] = f'attachment; filename="lightpdf_{int(time.time())}.pdf"' return resp except Exception as e: print("PDF生成错误:", e) return "解析失败:生成异常", 500 if __name__ == "__main__": app.run(host="0.0.0.0", port=9002, debug=False)