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

如何将ZXing生成的条码直接插入PDF(无需保存本地图片)

直接将ZXing生成的条码插入PDF(跳过本地图片保存)

可以通过**内存流(MemoryStream)**中转ZXing生成的Bitmap,直接转换为PDFsharp支持的XImage,完全跳过本地图片保存步骤。以下是整合后的完整代码,同时支持用户自定义条码位置:

using System.IO;
using System.Drawing;
using ZXing;
using ZXing.Common;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Diagnostics;

// 1. 生成条码Bitmap
BarcodeWriter writer = new BarcodeWriter()
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = 100,
        Width = 200,
        PureBarcode = false,
        Margin = 10,
    },
};

string itemnumber = @"*\" + textBox1.Text + "*"; 
var bitmap = writer.Write(itemnumber);

// 2. 用MemoryStream中转,无需保存本地文件
XImage barcodeXImage;
using (MemoryStream ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    ms.Position = 0; // 重置流指针到起始位置,确保XImage能正确读取
    barcodeXImage = XImage.FromStream(ms);
}

// 3. 创建PDF并插入条码到指定位置
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);

// 自定义位置:可通过文本框让用户输入坐标和尺寸,这里示例从文本框读取(需提前在界面添加对应控件)
float posX = float.TryParse(textBoxPosX.Text, out float x) ? x : 220;
float posY = float.TryParse(textBoxPosY.Text, out float y) ? y : 120;
float imgWidth = float.TryParse(textBoxImgWidth.Text, out float w) ? w : 50;
float imgHeight = float.TryParse(textBoxImgHeight.Text, out float h) ? h : 50;

// 将条码绘制到PDF指定位置
gfx.DrawImage(barcodeXImage, posX, posY, imgWidth, imgHeight);

// 保存并打开生成的PDF
string filename = "Barcode.pdf";
document.Save(filename);
Process.Start(filename);

关键细节说明:

  • 内存流替代本地文件:用MemoryStream在内存中完成Bitmap到XImage的转换,省去磁盘IO操作,提升效率
  • 用户自定义配置:通过添加textBoxPosX、textBoxPosY等文本框,让用户直接输入条码的位置坐标和显示尺寸,代码中用float.TryParse做容错处理,避免无效输入崩溃
  • 资源自动释放:用using语句包裹MemoryStream,确保流资源在使用后被自动释放,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:07:35