package pdf import ( "bytes" "encoding/base64" "fmt" "image" "image/jpeg" "image/png" "regexp" "strconv" "strings" "unicode" "codeberg.org/go-pdf/fpdf" "golang.org/x/image/font/gofont/gobold" "golang.org/x/image/font/gofont/gobolditalic" "golang.org/x/image/font/gofont/goitalic" "golang.org/x/image/font/gofont/goregular" "golang.org/x/image/webp" "cotizador/internal/domain" ) const ( fontFamily = "Go" defaultPrimary = "#0400C4" defaultDark = "#0F172A" colorMuted = "#64748b" colorBorder = "#cbd5e1" colorLightBG = "#f1f5f9" colorWhite = "#ffffff" colorSubtleSep = "#e5e7eb" ) var ( hexColorRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) swiftRe = regexp.MustCompile(`(?i)SWIFT[^:]*:\s*(\S+)`) clabeRe = regexp.MustCompile(`(?i)CLABE[^:]*:\s*(\S+)`) ) func safeHex(v, fallback string) string { v = strings.TrimSpace(v) if hexColorRe.MatchString(v) { return v } return fallback } func parseHexRGB(hexStr, fallback string) (int, int, int) { h := strings.TrimPrefix(safeHex(hexStr, fallback), "#") r, _ := strconv.ParseInt(h[0:2], 16, 64) g, _ := strconv.ParseInt(h[2:4], 16, 64) b, _ := strconv.ParseInt(h[4:6], 16, 64) return int(r), int(g), int(b) } func capitalize(s string) string { s = strings.TrimSpace(s) if s == "" { return "" } r := []rune(s) r[0] = unicode.ToUpper(r[0]) return string(r) } func formatMoney(amount float64, moneda string) string { if moneda == "" || strings.EqualFold(moneda, "MXN") { return domain.FormatCurrency(amount) } return domain.FormatMonto(amount, moneda) } type bankInfo struct { RazonSocial string RFC string CuentaNacional string ClabeNacional string BancoNacional string ClabeInternacional string Swift string } func extractBankInfo(cfg map[string]string) bankInfo { if cfg == nil { cfg = map[string]string{} } razon := strings.TrimSpace(cfg["razon_social"]) if razon == "" { razon = "URIEL JARETH ALVARADO ORTIZ" } rfc := strings.TrimSpace(cfg["rfc"]) if rfc == "" { rfc = "AAOU970201SU7" } cuentaNac := strings.TrimSpace(cfg["cuenta_nacional"]) clabeNac := strings.TrimSpace(cfg["clabe_interbancaria"]) if clabeNac == "" { clabeNac = cuentaNac } bancoNac := "" if cuentaNac != "" { bancoNac = "BBVA" } swift := "BCMRMXMMPYM" clabeInt := "" if intl := cfg["cuenta_internacional_swift"]; intl != "" { if m := swiftRe.FindStringSubmatch(intl); len(m) > 1 { swift = m[1] } if m := clabeRe.FindStringSubmatch(intl); len(m) > 1 { clabeInt = m[1] } } return bankInfo{ RazonSocial: razon, RFC: rfc, CuentaNacional: cuentaNac, ClabeNacional: clabeNac, BancoNacional: bancoNac, ClabeInternacional: clabeInt, Swift: swift, } } type logoAsset struct { name string w float64 h float64 ok bool } // prepareLogoBytes decodes base64 and normalizes PNG/JPEG/WebP into a format fpdf safely accepts. // WebP (and non-standard PNGs) are decoded and re-encoded as standard 8-bit PNG. func prepareLogoBytes(b64, mime string) ([]byte, string, error) { b64 = strings.TrimSpace(b64) if b64 == "" { return nil, "", fmt.Errorf("empty logo") } // Strip optional data URI prefix. if idx := strings.Index(b64, ","); idx != -1 && strings.HasPrefix(b64[:idx], "data:") { if mime == "" { header := b64[len("data:"):idx] if semi := strings.Index(header, ";"); semi != -1 { mime = header[:semi] } } b64 = b64[idx+1:] } raw, err := base64.StdEncoding.DecodeString(b64) if err != nil { raw, err = base64.RawStdEncoding.DecodeString(b64) if err != nil { return nil, "", err } } if len(raw) < 8 { return nil, "", fmt.Errorf("logo too short") } m := strings.ToLower(strings.TrimSpace(mime)) isWebP := m == "image/webp" || (len(raw) >= 12 && string(raw[0:4]) == "RIFF" && string(raw[8:12]) == "WEBP") if isWebP { img, err := webp.Decode(bytes.NewReader(raw)) if err != nil { return nil, "", err } var out bytes.Buffer if err := png.Encode(&out, img); err != nil { return nil, "", err } return out.Bytes(), "PNG", nil } isJPEG := m == "image/jpeg" || m == "image/jpg" || (raw[0] == 0xFF && raw[1] == 0xD8) if isJPEG { if _, err := jpeg.DecodeConfig(bytes.NewReader(raw)); err != nil { return nil, "", err } return raw, "JPG", nil } isPNG := m == "image/png" || bytes.Equal(raw[0:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}) if isPNG { // Re-encode through image/png so interlaced or 16-bit PNGs always work with fpdf. img, err := png.Decode(bytes.NewReader(raw)) if err != nil { return nil, "", err } var out bytes.Buffer if err := png.Encode(&out, img); err != nil { return nil, "", err } return out.Bytes(), "PNG", nil } // Fallback: try generic image decode -> PNG. img, _, err := image.Decode(bytes.NewReader(raw)) if err != nil { return nil, "", err } var out bytes.Buffer if err := png.Encode(&out, img); err != nil { return nil, "", err } return out.Bytes(), "PNG", nil } func registerLogo(doc *fpdf.Fpdf, name, b64, mime string) logoAsset { imgBytes, imgType, err := prepareLogoBytes(b64, mime) if err != nil { return logoAsset{} } opts := fpdf.ImageOptions{ImageType: imgType, ReadDpi: false} info := doc.RegisterImageOptionsReader(name, opts, bytes.NewReader(imgBytes)) if info == nil || !doc.Ok() { doc.ClearError() return logoAsset{} } return logoAsset{ name: name, w: info.Width(), h: info.Height(), ok: info.Width() > 0 && info.Height() > 0, } } func (l logoAsset) drawByHeight(doc *fpdf.Fpdf, x, y, targetH float64) { if !l.ok { return } doc.ImageOptions(l.name, x, y, 0, targetH, false, fpdf.ImageOptions{}, 0, "") } func (l logoAsset) drawRightAlignedByHeight(doc *fpdf.Fpdf, rightX, y, targetH float64) { if !l.ok { return } w := targetH * (l.w / l.h) if w > 90 { w = 90 targetH = w * (l.h / l.w) } doc.ImageOptions(l.name, rightX-w, y, w, targetH, false, fpdf.ImageOptions{}, 0, "") } func (l logoAsset) drawFit(doc *fpdf.Fpdf, x, y, maxW, maxH float64) (float64, float64) { if !l.ok { return 0, 0 } scale := maxW / l.w if sh := maxH / l.h; sh < scale { scale = sh } w := l.w * scale h := l.h * scale doc.ImageOptions(l.name, x, y, w, h, false, fpdf.ImageOptions{}, 0, "") return w, h } type canvas struct { doc *fpdf.Fpdf pw float64 ph float64 mTop float64 mBottom float64 mLeft float64 mRight float64 W float64 L float64 maxY float64 } func newCanvas(top, bottom, left, right float64) *canvas { doc := fpdf.New("P", "pt", "Letter", "") doc.AddUTF8FontFromBytes(fontFamily, "", goregular.TTF) doc.AddUTF8FontFromBytes(fontFamily, "B", gobold.TTF) doc.AddUTF8FontFromBytes(fontFamily, "I", goitalic.TTF) doc.AddUTF8FontFromBytes(fontFamily, "BI", gobolditalic.TTF) doc.SetMargins(left, top, right) doc.SetAutoPageBreak(false, 0) doc.SetCellMargin(0) doc.SetFont(fontFamily, "", 10) pw, ph := doc.GetPageSize() return &canvas{ doc: doc, pw: pw, ph: ph, mTop: top, mBottom: bottom, mLeft: left, mRight: right, W: pw - left - right, L: left, maxY: ph - bottom - 5, } } func (c *canvas) need(h, y float64) float64 { if y+h > c.maxY { c.doc.AddPage() return c.mTop } return y } func (c *canvas) setFont(style string, size float64) { c.doc.SetFont(fontFamily, style, size) } func (c *canvas) setTextColor(hex string) { r, g, b := parseHexRGB(hex, defaultDark) c.doc.SetTextColor(r, g, b) } func (c *canvas) setFillColor(hex string) { r, g, b := parseHexRGB(hex, colorWhite) c.doc.SetFillColor(r, g, b) } func (c *canvas) setDrawColor(hex string) { r, g, b := parseHexRGB(hex, colorBorder) c.doc.SetDrawColor(r, g, b) } func lineHeight(size float64) float64 { return size * 1.25 } func (c *canvas) splitLines(txt string, width float64, style string, size float64) []string { c.setFont(style, size) if width <= 1 { return []string{txt} } rawLines := strings.Split(strings.ReplaceAll(txt, "\r\n", "\n"), "\n") var out []string for _, rl := range rawLines { if rl == "" { out = append(out, "") continue } parts := c.doc.SplitText(rl, width) if len(parts) == 0 { out = append(out, rl) } else { out = append(out, parts...) } } if len(out) == 0 { return []string{""} } return out } func (c *canvas) textHeight(txt string, width float64, style string, size float64) float64 { lines := c.splitLines(txt, width, style, size) return float64(len(lines)) * lineHeight(size) } // drawText writes multi-line wrapped text starting at (x, y) and returns total height drawn. func (c *canvas) drawText(txt string, x, y, width float64, style string, size float64, color, align string) float64 { if align == "" { align = "L" } lines := c.splitLines(txt, width, style, size) lh := lineHeight(size) c.setFont(style, size) c.setTextColor(color) curY := y for _, ln := range lines { c.doc.SetXY(x, curY) c.doc.CellFormat(width, lh, ln, "", 0, align, false, 0, "") curY += lh } return float64(len(lines)) * lh } // drawSingleLine writes text on one line without wrapping. func (c *canvas) drawSingleLine(txt string, x, y, width float64, style string, size float64, color, align string) { if align == "" { align = "L" } c.setFont(style, size) c.setTextColor(color) c.doc.SetXY(x, y) if width <= 0 { width = c.doc.GetStringWidth(txt) + 2 } c.doc.CellFormat(width, lineHeight(size), txt, "", 0, align, false, 0, "") } func (c *canvas) rectFill(x, y, w, h float64, fillHex string) { c.setFillColor(fillHex) c.doc.Rect(x, y, w, h, "F") } func (c *canvas) rectFillStroke(x, y, w, h float64, fillHex, strokeHex string, lw float64) { c.setFillColor(fillHex) c.setDrawColor(strokeHex) c.doc.SetLineWidth(lw) c.doc.Rect(x, y, w, h, "DF") } func (c *canvas) hLine(x1, x2, y float64, strokeHex string, lw float64) { c.setDrawColor(strokeHex) c.doc.SetLineWidth(lw) c.doc.Line(x1, y, x2, y) } func (c *canvas) circleFill(cx, cy, r float64, fillHex string) { c.setFillColor(fillHex) c.doc.Circle(cx, cy, r, "F") } func (c *canvas) rowBg(y, h float64, bgHex string) { c.rectFill(c.L, y, c.W, h, bgHex) c.hLine(c.L, c.L+c.W, y+h, colorBorder, 0.3) } func (c *canvas) bytes() ([]byte, error) { var buf bytes.Buffer if err := c.doc.Output(&buf); err != nil { return nil, err } return buf.Bytes(), nil }