using QuestPDF.Drawing; namespace Oms.Application.Labeling.Hiprint; /// /// 面单 PDF 中文字体:QuestPDF 默认字体无 CJK,不注册会显示 □ / ?。 /// public static class LabelPdfFontRegistrar { public const string FamilyName = "OmsLabelSans"; private static int _state; // 0=未试 1=成功 2=失败 private static string? _sourcePath; /// /// 确保已注册可用中文字体;成功返回 ,否则 null(仅西文)。 /// public static string? EnsureRegistered() { var state = Volatile.Read(ref _state); if (state == 1) { return FamilyName; } if (state == 2) { return null; } foreach (var path in EnumerateCandidates()) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { continue; } try { using var stream = File.OpenRead(path); FontManager.RegisterFontWithCustomName(FamilyName, stream); _sourcePath = path; Interlocked.Exchange(ref _state, 1); return FamilyName; } catch { // 试下一个候选 } } Interlocked.Exchange(ref _state, 2); return null; } /// 已成功注册时的字体文件路径(诊断用)。 public static string? RegisteredSourcePath => _sourcePath; private static IEnumerable EnumerateCandidates() { var fromEnv = Environment.GetEnvironmentVariable("OMS_LABEL_FONT"); if (!string.IsNullOrWhiteSpace(fromEnv)) { yield return fromEnv.Trim(); } var baseDir = AppContext.BaseDirectory; yield return Path.Combine(baseDir, "Fonts", "NotoSansSC-Regular.otf"); yield return Path.Combine(baseDir, "Fonts", "NotoSansSC-Regular.ttf"); yield return Path.Combine(baseDir, "Fonts", "NotoSansCJKsc-Regular.otf"); // Windows var winFonts = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); if (!string.IsNullOrWhiteSpace(winFonts)) { yield return Path.Combine(winFonts, "msyh.ttc"); yield return Path.Combine(winFonts, "msyhbd.ttc"); yield return Path.Combine(winFonts, "simhei.ttf"); yield return Path.Combine(winFonts, "simsun.ttc"); } // Debian/Ubuntu(Dockerfile 安装 fonts-noto-cjk) yield return "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"; yield return "/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf"; yield return "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"; yield return "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"; } }