This commit is contained in:
2026-03-11 17:23:09 +08:00
parent ba1a72aa8f
commit 67c6e2e144
4 changed files with 1895 additions and 27 deletions

View File

@@ -3,6 +3,7 @@ package pdf
import (
"os"
"path/filepath"
"runtime"
"github.com/jung-kurt/gofpdf/v2"
"go.uber.org/zap"
@@ -131,22 +132,20 @@ func (fm *FontManager) tryAddFont(pdf *gofpdf.Fpdf, fontPath, fontName string) b
// 注意ToSlash不会改变路径的绝对/相对性质,只统一分隔符
normalizedPath := filepath.ToSlash(absFontPath)
// 在Linux下绝对路径必须以/开头
// 如果normalizedPath不是以/开头,说明转换有问题
if len(normalizedPath) == 0 || normalizedPath[0] != '/' {
fm.logger.Error("字体路径转换后不是绝对路径(不以/开头)",
// 在 Linux 下,绝对路径通常以 / 开头;在 Windows 下则可能以盘符 (C:/...) 开头
// 这里只要保证 normalizedPath 非空即可,具体格式交给 gofpdf 处理,避免在 Windows 下误判。
if len(normalizedPath) == 0 {
fm.logger.Error("字体路径转换后为空无法添加到PDF",
zap.String("abs_font_path", absFontPath),
zap.String("normalized_path", normalizedPath),
zap.String("font_name", fontName),
)
// 重新转换为绝对路径
if newAbsPath, err := filepath.Abs(absFontPath); err == nil {
absFontPath = newAbsPath
normalizedPath = filepath.ToSlash(newAbsPath)
fm.logger.Info("重新转换后的路径",
zap.String("new_normalized_path", normalizedPath),
)
}
return false
}
// 额外记录当前平台,方便排查路径格式问题
fm.logger.Debug("字体路径平台信息",
zap.String("goos", runtime.GOOS),
zap.String("normalized_path", normalizedPath),
)
fm.logger.Debug("准备添加字体到gofpdf",
zap.String("original_path", fontPath),
@@ -157,16 +156,6 @@ func (fm *FontManager) tryAddFont(pdf *gofpdf.Fpdf, fontPath, fontName string) b
// gofpdf v2使用AddUTF8Font添加支持UTF-8的字体
// 注意gofpdf在Output时可能会重新解析路径必须确保路径格式正确
// 关键:确保路径是绝对路径且以/开头并使用filepath.ToSlash统一分隔符
// 如果normalizedPath不是以/开头,说明路径有问题,需要重新处理
if len(normalizedPath) == 0 || normalizedPath[0] != '/' {
fm.logger.Error("字体路径格式错误无法添加到PDF",
zap.String("normalized_path", normalizedPath),
zap.String("font_name", fontName),
)
return false
}
// 记录传递给gofpdf的实际路径
fm.logger.Info("添加字体到gofpdf",
zap.String("font_path", normalizedPath),