diff --git a/src/Oms.Application/Fonts/OmsLabelCjk.ttf b/src/Oms.Application/Fonts/OmsLabelCjk.ttf new file mode 100644 index 0000000..1f1bdf8 Binary files /dev/null and b/src/Oms.Application/Fonts/OmsLabelCjk.ttf differ diff --git a/src/Oms.Application/Fonts/README.md b/src/Oms.Application/Fonts/README.md new file mode 100644 index 0000000..3059493 --- /dev/null +++ b/src/Oms.Application/Fonts/README.md @@ -0,0 +1,5 @@ +# 面单 PDF 中文字体 + +`OmsLabelCjk.ttf`:随程序嵌入,供 QuestPDF 渲染箱唛/SKU 中文(避免默认字体缺字形显示 `?`/`□`)。 + +部署镜像无需再依赖系统 Noto;仍可通过环境变量 `OMS_LABEL_FONT` 覆盖为其它 ttf/otf。 diff --git a/src/Oms.Application/Labeling/Hiprint/LabelPdfFontRegistrar.cs b/src/Oms.Application/Labeling/Hiprint/LabelPdfFontRegistrar.cs index ee65228..4003af5 100644 --- a/src/Oms.Application/Labeling/Hiprint/LabelPdfFontRegistrar.cs +++ b/src/Oms.Application/Labeling/Hiprint/LabelPdfFontRegistrar.cs @@ -1,19 +1,23 @@ +using System.Reflection; using QuestPDF.Drawing; namespace Oms.Application.Labeling.Hiprint; /// -/// 面单 PDF 中文字体:QuestPDF 默认字体无 CJK,不注册会显示 □ / ?。 +/// 面单 PDF 中文字体:QuestPDF 默认字体无 CJK;优先嵌入字体,避免依赖容器内 TTC。 /// public static class LabelPdfFontRegistrar { public const string FamilyName = "OmsLabelSans"; + private const string EmbeddedName = "Oms.Application.Fonts.OmsLabelCjk.ttf"; + private static int _state; // 0=未试 1=成功 2=失败 - private static string? _sourcePath; + private static string? _source; + private static string? _lastError; /// - /// 确保已注册可用中文字体;成功返回 ,否则 null(仅西文)。 + /// 确保已注册可用中文字体;成功返回 ,否则 null。 /// public static string? EnsureRegistered() { @@ -28,24 +32,28 @@ public static class LabelPdfFontRegistrar return null; } - foreach (var path in EnumerateCandidates()) + foreach (var attempt in EnumerateAttempts()) { - if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) - { - continue; - } - try { - using var stream = File.OpenRead(path); - FontManager.RegisterFontWithCustomName(FamilyName, stream); - _sourcePath = path; + using var stream = attempt.Open(); + if (stream == null || stream.Length == 0) + { + continue; + } + + // 读入内存:Register 后不可依赖外部流生命周期;并规避部分 TTC 流问题 + using var ms = new MemoryStream(); + stream.CopyTo(ms); + ms.Position = 0; + FontManager.RegisterFontWithCustomName(FamilyName, ms); + _source = attempt.Description; Interlocked.Exchange(ref _state, 1); return FamilyName; } - catch + catch (Exception ex) { - // 试下一个候选 + _lastError = $"{attempt.Description}: {ex.Message}"; } } @@ -53,36 +61,60 @@ public static class LabelPdfFontRegistrar return null; } - /// 已成功注册时的字体文件路径(诊断用)。 - public static string? RegisteredSourcePath => _sourcePath; + public static string? RegisteredSource => _source; - private static IEnumerable EnumerateCandidates() + public static string? LastError => _lastError; + + private static IEnumerable EnumerateAttempts() { + yield return new FontAttempt( + "embedded:" + EmbeddedName, + () => Assembly.GetExecutingAssembly().GetManifestResourceStream(EmbeddedName)); + var fromEnv = Environment.GetEnvironmentVariable("OMS_LABEL_FONT"); if (!string.IsNullOrWhiteSpace(fromEnv)) { - yield return fromEnv.Trim(); + var path = fromEnv.Trim(); + yield return new FontAttempt("env:" + path, () => File.Exists(path) ? File.OpenRead(path) : null); } 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"); + foreach (var name in new[] + { + "OmsLabelCjk.ttf", + "NotoSansSC-Regular.otf", + "NotoSansSC-Regular.ttf", + "NotoSansCJKsc-Regular.otf", + "simhei.ttf" + }) + { + var path = Path.Combine(baseDir, "Fonts", name); + yield return new FontAttempt("file:" + path, () => File.Exists(path) ? File.OpenRead(path) : null); + } - // 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"); + // 单文件 TTF 优先于 TTC(集合字体在部分 Skia 版本上注册失败/缺简体) + foreach (var name in new[] { "simhei.ttf", "msyh.ttc", "msyhbd.ttc", "simsun.ttc" }) + { + var path = Path.Combine(winFonts, name); + yield return new FontAttempt("win:" + path, () => File.Exists(path) ? File.OpenRead(path) : null); + } } - // 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"; + foreach (var path in new[] + { + "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", + "/usr/share/fonts/truetype/arphic/uming.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc" + }) + { + yield return new FontAttempt("linux:" + path, () => File.Exists(path) ? File.OpenRead(path) : null); + } } + + private readonly record struct FontAttempt(string Description, Func Open); } diff --git a/src/Oms.Application/Labeling/Hiprint/QuestPdfLabelRenderer.cs b/src/Oms.Application/Labeling/Hiprint/QuestPdfLabelRenderer.cs index 3472a49..061a574 100644 --- a/src/Oms.Application/Labeling/Hiprint/QuestPdfLabelRenderer.cs +++ b/src/Oms.Application/Labeling/Hiprint/QuestPdfLabelRenderer.cs @@ -23,8 +23,9 @@ public sealed class QuestPdfLabelRenderer(HiprintTemplateParser parser) : ILabel CancellationToken cancellationToken = default) { EnsureLicense(); - // SKU 名称等含中文;未注册 CJK 字体会输出 □ - _ = LabelPdfFontRegistrar.EnsureRegistered(); + var fontFamily = LabelPdfFontRegistrar.EnsureRegistered() + ?? throw new InvalidOperationException( + "面单中文字体未就绪:" + (LabelPdfFontRegistrar.LastError ?? "未找到可用 CJK 字体")); cancellationToken.ThrowIfCancellationRequested(); if (printDataPages == null || printDataPages.Count == 0) @@ -50,13 +51,15 @@ public sealed class QuestPdfLabelRenderer(HiprintTemplateParser parser) : ILabel { page.Size(pageWidthPt, pageHeightPt); page.Margin(0); + // 页级默认中文字体;单元素再设字号/颜色。勿对嵌入 Regular 调 Bold(会回退缺字西文字体 → ???) + page.DefaultTextStyle(x => x.FontFamily(fontFamily).FontColor(Colors.Black)); page.Content().Layers(layers => { layers.PrimaryLayer().Background(Colors.White); foreach (var op in pageIr.Ops) { - DrawOp(layers, op); + DrawOp(layers, op, fontFamily); } }); }); @@ -66,7 +69,7 @@ public sealed class QuestPdfLabelRenderer(HiprintTemplateParser parser) : ILabel return Task.FromResult(bytes); } - private static void DrawOp(LayersDescriptor layers, LabelDrawOp op) + private static void DrawOp(LayersDescriptor layers, LabelDrawOp op, string fontFamily) { switch (op) { @@ -86,22 +89,16 @@ public sealed class QuestPdfLabelRenderer(HiprintTemplateParser parser) : ILabel _ => box.AlignLeft() }; - var span = aligned - .AlignTop() - .Text(text.Text) - .FontSize(text.FontSizePt) - .FontColor(ParseColor(text.ColorHex)); - - var fontFamily = LabelPdfFontRegistrar.EnsureRegistered(); - if (!string.IsNullOrEmpty(fontFamily)) + aligned.AlignTop().Text(t => { - span.FontFamily(fontFamily); - } - - if (text.Bold) - { - span.Bold(); - } + // 勿对嵌入 Regular 调用 Bold():会回退缺字西文字体,中文变成 ??? + var size = text.Bold ? text.FontSizePt * 1.02f : text.FontSizePt; + t.DefaultTextStyle(style => style + .FontFamily(fontFamily) + .FontSize(size) + .FontColor(ParseColor(text.ColorHex))); + t.Span(text.Text ?? string.Empty); + }); break; } @@ -168,6 +165,8 @@ public sealed class QuestPdfLabelRenderer(HiprintTemplateParser parser) : ILabel } QuestPDF.Settings.License = LicenseType.Community; + // 缺字形时不抛,但仍应依赖嵌入 CJK 字体 + QuestPDF.Settings.CheckIfAllTextGlyphsAreAvailable = false; } private static float MmToPt(float mm) => mm * 72f / 25.4f; diff --git a/src/Oms.Application/Oms.Application.csproj b/src/Oms.Application/Oms.Application.csproj index 63f8eff..35e7187 100644 --- a/src/Oms.Application/Oms.Application.csproj +++ b/src/Oms.Application/Oms.Application.csproj @@ -41,6 +41,13 @@ + + + + + + + diff --git a/src/Oms.Tests/LabelPdfFontTests.cs b/src/Oms.Tests/LabelPdfFontTests.cs new file mode 100644 index 0000000..3dd87f6 --- /dev/null +++ b/src/Oms.Tests/LabelPdfFontTests.cs @@ -0,0 +1,56 @@ +using FluentAssertions; +using Oms.Application.Labeling.Hiprint; + +namespace Oms.Tests; + +public class LabelPdfFontTests +{ + [Fact] + public void EnsureRegistered_ShouldLoadEmbeddedCjkFont() + { + var family = LabelPdfFontRegistrar.EnsureRegistered(); + + family.Should().Be(LabelPdfFontRegistrar.FamilyName); + LabelPdfFontRegistrar.RegisteredSource.Should().NotBeNullOrWhiteSpace(); + LabelPdfFontRegistrar.RegisteredSource.Should().StartWith("embedded:"); + } + + [Fact] + public async Task Render_ShouldEmbedChineseWithoutThrowing() + { + LabelPdfFontRegistrar.EnsureRegistered().Should().NotBeNull(); + + const string templateJson = """ + { + "panels": [{ + "width": 100, + "height": 50, + "printElements": [{ + "options": { + "left": 2, + "top": 2, + "width": 90, + "height": 20, + "title": "红米手机 摘要×25", + "fontSize": 12 + }, + "printElementType": { "type": "text" } + }] + }] + } + """; + + var renderer = new QuestPdfLabelRenderer(new HiprintTemplateParser()); + var pdf = await renderer.RenderAsync( + templateJson, + new Dictionary { ["skuSummary"] = "红米手机 512g×25" }); + + pdf.Should().NotBeNull(); + pdf.Length.Should().BeGreaterThan(500); + // RegisterFontWithCustomName 后 PDF 仍写入真实 PostScript 名(如 SimHei) + var ascii = System.Text.Encoding.ASCII.GetString(pdf); + ascii.Should().Match(s => s.Contains("SimHei", StringComparison.OrdinalIgnoreCase) + || s.Contains("OmsLabelSans", StringComparison.OrdinalIgnoreCase) + || s.Contains("Noto", StringComparison.OrdinalIgnoreCase)); + } +}