package handler import ( "bytes" "context" "fmt" "net/http" "strconv" "strings" "bj_power_mes/common/httpx" "bj_power_mes/internal/svc" "github.com/jung-kurt/gofpdf" ) const ( pdfMargin = 12.0 pdfLineH = 5.0 pdfPageW = 210.0 pdfPageH = 297.0 pdfBottom = pdfPageH - pdfMargin ) // WorkOrderCardPdfHandler GET /api/v1/process-card/pdf?no=WO-1&no=WO-2&sn=FIN-1 // 服务端生成真正的 PDF 文件(不再依赖浏览器「打印→另存为」),支持多张卡合并到一个 PDF。 func WorkOrderCardPdfHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() nos := q["no"] sns := q["sn"] if len(nos) == 0 && len(sns) == 0 { httpx.BadRequest(w, "缺少 no 或 sn 参数") return } pdf, err := buildCardsPdf(r.Context(), svcCtx, nos, sns) if err != nil { httpx.Fail(w, 2410, err.Error()) return } var buf bytes.Buffer if err := pdf.Output(&buf); err != nil { httpx.Fail(w, 2411, "PDF 生成失败:"+err.Error()) return } filename := "流程卡批量导出" if len(nos) == 1 && len(sns) == 0 { filename = "生产流程卡_" + nos[0] } else if len(sns) == 1 && len(nos) == 0 { filename = "成品追溯卡_" + sns[0] } w.Header().Set("Content-Type", "application/pdf") w.Header().Set("Content-Disposition", `attachment; filename="process_card.pdf"; filename*=UTF-8''`+urlEncode(filename+".pdf")) _, _ = w.Write(buf.Bytes()) } } func urlEncode(s string) string { var b strings.Builder for _, r := range s { if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == '~' { b.WriteRune(r) } else { b.WriteString("%" + strings.ToUpper(strconv.FormatInt(int64(r), 16))) } } return b.String() } // buildCardsPdf 生成包含若干工单主卡 / 成品 SN 追溯卡的 PDF 文档。 func buildCardsPdf(ctx context.Context, svcCtx *svc.ServiceContext, nos, sns []string) (*gofpdf.Fpdf, error) { pdf := gofpdf.New("P", "mm", "A4", "") fontBytes, err := simheiFontFS.ReadFile("fonts/simhei.ttf") if err != nil { return nil, fmt.Errorf("字体读取失败:%w", err) } pdf.AddUTF8FontFromBytes("simhei", "", fontBytes) if pdf.Err() { return nil, fmt.Errorf("中文字体加载失败") } pdf.SetFooterFunc(func() { pdf.SetFont("simhei", "", 8) pdf.SetTextColor(120, 120, 120) pdf.SetY(pdfPageH - 8) pdfCell(pdf, pdfPageW, 6, strconv.Itoa(pdf.PageNo()), "", "C", false, 0) pdf.SetTextColor(0, 0, 0) }) pdf.SetMargins(pdfMargin, pdfMargin, pdfMargin) first := true for _, no := range nos { card, err := buildWorkOrderCard(ctx, svcCtx, no) if err != nil { return nil, err } if !first { pdf.AddPage() } first = false renderWorkOrderCardPdf(pdf, card) } for _, sn := range sns { card, err := buildSnTraceCard(ctx, svcCtx, sn) if err != nil { return nil, err } if !first { pdf.AddPage() } first = false renderSnTraceCardPdf(pdf, card) } if first { pdf.AddPage() } return pdf, nil } // pdfCell 封装 gofpdf.CellFormat(统一 link 参数)。 func pdfCell(pdf *gofpdf.Fpdf, w, h float64, txt, border, align string, fill bool, ln int) { pdf.CellFormat(w, h, txt, border, ln, align, fill, 0, "") } // ---------- 通用绘制助手 ---------- func pdfSetFont(pdf *gofpdf.Fpdf, size float64) { pdf.SetFont("simhei", "", size) } // wrap 按字符宽度折行(兼容中文逐字与西文按空格)。 func wrap(pdf *gofpdf.Fpdf, text string, maxW float64) []string { if text == "" { return []string{""} } lines := []string{} cur := strings.Builder{} curW := 0.0 for _, r := range text { s := string(r) w := pdf.GetStringWidth(s) if curW+w > maxW && cur.Len() > 0 { lines = append(lines, cur.String()) cur.Reset() curW = 0 } cur.WriteString(s) curW += w } if cur.Len() > 0 { lines = append(lines, cur.String()) } if len(lines) == 0 { lines = []string{""} } return lines } func pdfTitle(pdf *gofpdf.Fpdf, y float64, txt string) float64 { pdfSetFont(pdf, 17) pdf.SetXY(pdfMargin, y) pdfCell(pdf, pdfPageW-2*pdfMargin, 10, txt, "", "C", false, 0) return y + 12 } func pdfHeading(pdf *gofpdf.Fpdf, y float64, txt string) float64 { if y > pdfBottom-10 { pdf.AddPage() y = pdfMargin } pdfSetFont(pdf, 12) pdf.SetXY(pdfMargin, y) pdfCell(pdf, pdfPageW-2*pdfMargin, 8, txt, "", "L", false, 0) pdf.Line(pdfMargin, y+8.5, pdfPageW-pdfMargin, y+8.5) return y + 12 } // metaKV 打印「标签:值」键值对,每行 perRow 组,自动换行。 func metaKV(pdf *gofpdf.Fpdf, y float64, pairs [][2]string, perRow int) float64 { pdfSetFont(pdf, 10) gap := (pdfPageW - 2*pdfMargin) / float64(perRow) for i := 0; i < len(pairs); i += perRow { if y > pdfBottom-pdfLineH { pdf.AddPage() y = pdfMargin } x := pdfMargin for j := 0; j < perRow && i+j < len(pairs); j++ { p := pairs[i+j] pdf.SetXY(x, y) pdfCell(pdf, gap-2, pdfLineH, p[0]+":"+p[1], "", "L", false, 0) x += gap } y += pdfLineH } return y + 2 } // drawTable 绘制表格(含表头),自动处理分页与多行单元格。 func drawTable(pdf *gofpdf.Fpdf, y float64, widths []float64, headers []string, rows [][]string) float64 { y = drawRow(pdf, y, widths, headers, true, headers) for _, row := range rows { y = drawRow(pdf, y, widths, row, false, headers) } return y + 2 } func drawRow(pdf *gofpdf.Fpdf, y float64, widths []float64, cells []string, isHeader bool, headers []string) float64 { allLines := make([][]string, len(cells)) maxLines := 1 for i := range cells { w := widths[i] - 2 if w < 3 { w = 3 } ls := wrap(pdf, cells[i], w) allLines[i] = ls if len(ls) > maxLines { maxLines = len(ls) } } rowH := float64(maxLines) * pdfLineH if y+rowH > pdfBottom { pdf.AddPage() y = pdfMargin y = drawRow(pdf, y, widths, headers, true, headers) } xi := pdfMargin if isHeader { pdf.SetFillColor(243, 244, 246) } else { pdf.SetFillColor(255, 255, 255) } for i := range cells { pdf.SetXY(xi, y) pdfCell(pdf, widths[i], rowH, "", "1", "L", isHeader, 0) pdfSetFont(pdf, 9) ty := y lines := allLines[i] if len(lines) == 0 { lines = []string{""} } for _, line := range lines { pdf.SetXY(xi+1, ty+0.5) pdfCell(pdf, widths[i]-2, pdfLineH, line, "", "L", false, 0) ty += pdfLineH } xi += widths[i] } pdf.SetFillColor(255, 255, 255) return y + rowH } // pdfBlockFlags 四张子表的显示开关(2026-12-01 用户拍板):工艺没配置的块不绘制。 // 判断依据是「工艺里配没配」(工单级),不是「当前有没有数据」;单台追溯卡全开。 type pdfBlockFlags struct { Torque bool Sign bool Material bool } var pdfAllBlocks = pdfBlockFlags{Torque: true, Sign: true, Material: true} // drawProductTables 绘制一台成品的四张子表;工单主卡与单台追溯卡共用,保证导出结构一致。 func drawProductTables(pdf *gofpdf.Fpdf, y float64, p *woProduct, flags pdfBlockFlags) float64 { // ① 工序实绩 y = pdfHeading(pdf, y, "1. 工序实绩") stepRows := make([][]string, 0, len(p.Steps)) for _, s := range p.Steps { stepRows = append(stepRows, []string{ strconv.Itoa(s.Seq), s.ProcessName, s.StationNo, s.StartAt, s.EndAt, s.Operator, s.SelfCheck, s.Inspector, s.Conclusion, s.Remark, s.InspectedAt, s.Status, }) } y = drawTable(pdf, y, []float64{8, 26, 10, 20, 20, 18, 12, 14, 10, 20, 20, 8}, []string{"序号", "工艺", "工位", "开始", "结束", "操作人", "工人自检", "检验员", "结论", "检验意见", "检验时间", "状态"}, stepRows) // ② 用料清单(工艺没配物料分账 → 不绘制) if flags.Material { y = pdfHeading(pdf, y, "2. 用料清单") matRows := make([][]string, 0, len(p.Materials)) for _, m := range p.Materials { matRows = append(matRows, []string{ m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit, m.SnOrBatch, strconv.Itoa(m.Qty), m.StationNo, m.Operator, m.BindAt, }) } y = drawTable(pdf, y, []float64{24, 26, 14, 22, 10, 30, 8, 14, 20, 18}, []string{"图号", "名称", "类型", "规格", "单位", "物料SN或批次号", "数量", "装配工位", "装配人", "装配时间"}, matRows) } // ③ 拧紧数据(工艺没配拧紧步骤 → 不绘制) if flags.Torque { y = pdfHeading(pdf, y, "3. 拧紧数据") torqueRows := make([][]string, 0, len(p.Torques)) for _, t := range p.Torques { torqueRows = append(torqueRows, []string{t.ScrewNo, t.Torque, t.Angle, "设备判 " + t.Result, t.Operator, t.Time}) } y = drawTable(pdf, y, []float64{22, 26, 22, 26, 24, 66}, []string{"螺丝点", "扭矩", "角度", "设备判定", "操作人", "时间"}, torqueRows) } // ④ 签字明细(未撤销;工艺没配签字步骤 → 不绘制) if flags.Sign { y = pdfHeading(pdf, y, "4. 签字明细(未撤销)") signRows := make([][]string, 0, len(p.Signs)) for _, s := range p.Signs { signRows = append(signRows, []string{ s.ProcessName, s.StepName, s.SelfCheck, s.SelfCheckAt, s.Inspector, s.Conclusion, s.Remark, s.SignedAt, strconv.Itoa(s.Round), }) } y = drawTable(pdf, y, []float64{24, 20, 12, 22, 18, 12, 28, 34, 16}, []string{"工艺", "步骤", "工人自检", "自检时间", "检验员", "结论", "意见", "签字时间", "轮次"}, signRows) } return y } // ---------- 工单主卡 PDF ---------- func renderWorkOrderCardPdf(pdf *gofpdf.Fpdf, c *workOrderCard) { y := pdfMargin y = pdfTitle(pdf, y, "生产流程卡 · 工件明细") y = pdfHeading(pdf, y, "一、工单汇总") y = metaKV(pdf, y, [][2]string{ {"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode}, {"产品名称", c.ProductName}, {"图号", c.DrawingNo}, {"计划数", strconv.Itoa(c.PlanQty)}, {"完成数", strconv.Itoa(c.FinishedNum)}, {"不良数", strconv.Itoa(c.FailNum)}, {"用料合计", strconv.Itoa(c.MaterialTotal)}, {"状态", c.Status}, {"实际开始", c.ActualStart}, {"实际完成", c.ActualFinish}, {"生成时间", c.GeneratedAt}, }, 3) // 签字汇总:已排除撤销记录、按人去重,不再把返工重签算成次数。 sign := [][2]string{} if c.Signs.Operator != nil { sign = append(sign, [2]string{"操作工", c.Signs.Operator.Names + "(" + strconv.Itoa(c.Signs.Operator.Count) + "人,最近 " + c.Signs.Operator.LatestTime + ")"}) } else { sign = append(sign, [2]string{"操作工", "待签"}) } if c.Signs.Inspector != nil { sign = append(sign, [2]string{"检验员", c.Signs.Inspector.Names + "(" + strconv.Itoa(c.Signs.Inspector.Count) + "人,最近 " + c.Signs.Inspector.LatestTime + ")"}) } else { sign = append(sign, [2]string{"检验员", "待签"}) } y = metaKV(pdf, y, sign, 1) y = pdfHeading(pdf, y, "二、工件明细(按成品 SN 逐台)") if len(c.Products) == 0 { y = metaKV(pdf, y, [][2]string{{"提示", "暂无成品记录"}}, 1) } // 每台强制分页:一台一页,四张子表在页内按需续页。 for i := range c.Products { p := &c.Products[i] pdf.AddPage() y = pdfMargin y = pdfTitle(pdf, y, "成品 SN:"+p.Sn) y = metaKV(pdf, y, [][2]string{ {"状态", p.Status}, {"当前工序", p.CurrentProcess}, {"已完成工序", strconv.Itoa(p.DoneCount) + "/" + strconv.Itoa(p.TotalCount)}, {"用料条数", strconv.Itoa(p.MaterialCount)}, {"检验结论", p.InspectionResult}, {"完工时间", p.DoneAt}, }, 3) y = drawProductTables(pdf, y, p, pdfBlockFlags{ Torque: c.HasTorqueConfig, Sign: c.HasSignConfig, Material: c.HasMaterialConfig, }) _ = y } } // ---------- 成品 SN 追溯卡 PDF ---------- func renderSnTraceCardPdf(pdf *gofpdf.Fpdf, c *snTraceCard) { y := pdfMargin y = pdfTitle(pdf, y, "成品追溯卡 · 工件明细") y = metaKV(pdf, y, [][2]string{ {"SN", c.Sn}, {"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode}, {"状态", c.Status}, {"完工时间", c.DoneAt}, {"生成时间", c.GeneratedAt}, {"当前工序", c.CurrentProcess}, {"已完成工序", strconv.Itoa(c.DoneCount) + "/" + strconv.Itoa(c.TotalCount)}, {"用料条数", strconv.Itoa(c.MaterialCount)}, {"检验结论", c.InspectionResult}, }, 3) // 单台卡与工单主卡 products[] 使用同一套四张子表;单台卡不受工艺配置标志约束,四块全开。 p := &woProduct{Steps: c.Steps, Materials: c.Materials, Torques: c.Torques, Signs: c.SignRows} y = drawProductTables(pdf, y, p, pdfAllBlocks) if len(c.SkipRows) > 0 { y = pdfHeading(pdf, y, "5. 人工跳过(设备未连接)") srows := make([][]string, 0, len(c.SkipRows)) for _, s := range c.SkipRows { srows = append(srows, []string{s.StepName, s.Reason, s.Operator, s.Time}) } y = drawTable(pdf, y, []float64{40, 76, 24, 46}, []string{"拧紧步骤", "跳过原因", "操作人", "时间"}, srows) } _ = y }