You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ZXing.NET生成条码嵌入PDF后模糊无法正常扫描的问题排查

解决PDF中嵌入小条码模糊无法扫描的问题

核心问题分析

你当前的做法是生成小尺寸位图条码后强制拉伸嵌入PDF,这会导致栅格图缩放失真,条码线条边缘模糊、比例失调,扫描设备无法识别。另外,单纯设置DPI但原始像素数不足,也无法解决模糊问题。

解决方案

1. 生成高分辨率位图条码,按比例缩放嵌入

不要直接生成小尺寸条码,先生成足够大的位图保证像素密度,再按目标尺寸等比例缩小,避免强制拉伸变形:

// 生成条码的优化代码
BarcodeWriter writer = new BarcodeWriter()
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        // 生成大尺寸位图(对应300DPI下的2.4x1.33英寸)
        Height = 400,
        Width = 720,
        PureBarcode = false,
        Margin = 10,
        // 启用CODE128扩展模式,提升编码效率,减少条码宽度
        UseCode128ExtendedMode = true,
        // 控制条码密度,避免线条过密
        MinWidth = 2,
        MaxWidth = 2
    },
};

string content = @"*" + textBox1.Text + "*"; 
var bitmap = writer.Write(content);
// 设置正确的DPI,让PDFSharp识别缩放比例
bitmap.SetResolution(300, 300);

using (MemoryStream ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    GeneratePDF(ms);
}
// PDF嵌入的优化代码
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage pic = XImage.FromStream(ms);

// 按目标高度等比例计算宽度,避免拉伸变形
float targetHeight = 23;
float scaleRatio = targetHeight / pic.PixelHeight;
float targetWidth = pic.PixelWidth * scaleRatio;

gfx.DrawImage(pic, 220, 120, targetWidth, targetHeight);

2. 推荐:用矢量方式生成并绘制条码(完全不失真)

使用ZXing的矢量绑定包,直接生成矢量图形并在PDFSharp中绘制,彻底避免栅格图缩放问题:

首先安装NuGet包:ZXing.Net.Bindings.DrawingVector

然后修改代码:

// 生成矢量条码路径
BarcodeWriter<GraphicsPath> vectorWriter = new BarcodeWriter<GraphicsPath>()
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = 23, // 直接设置目标高度(PDF中的实际尺寸,单位:点)
        Width = 110, // 目标宽度
        PureBarcode = false,
        Margin = 10,
        UseCode128ExtendedMode = true
    },
    Renderer = new GraphicsPathRenderer()
};

string content = @"*" + textBox1.Text + "*"; 
GraphicsPath barcodePath = vectorWriter.Write(content);

// 在PDF中绘制矢量条码
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);

// 将GraphicsPath转换为XPath
XPath xPath = new XPath(barcodePath);
// 设置条码颜色
XPen pen = new XPen(XColors.Black, 1);
gfx.DrawPath(pen, xPath);
// 绘制文本(如果需要)
gfx.DrawString(content, new XFont("Arial", 8), XBrushes.Black, 
               new XPoint(220, 120 + 23), XStringFormats.TopLeft);

关键注意点

  • 不要强制拉伸条码的宽高比,保持原始比例是扫描识别的关键
  • CODE128条码的内容越长,需要的宽度越大,避免过度压缩导致线条重叠
  • 矢量方式生成的条码无论缩放多少倍都清晰,是小条码嵌入PDF的最优解

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:17:03