C#中使用iTextSharp嵌入二维码:PictureBox转Image失败问题
解决iTextSharp中嵌入Zen Barcode生成的二维码问题
我来帮你搞定这个问题——核心矛盾在于你拿到的是System.Drawing.Image(Zen Barcode和PictureBox用的都是这个),而iTextSharp需要的是它自己命名空间下的iTextSharp.text.Image,这俩是完全不同的类,没法直接强制转换。我们只需要通过内存流中转一下,就能把System.Drawing的图片转换成iTextSharp能识别的格式。
具体步骤和代码示例
直接跳过PictureBox的冗余环节(它只是用来显示图片的控件,完全没必要用它来中转二维码),直接处理Zen Barcode生成的图片:
using System.IO; using System.Drawing.Imaging; using iTextSharp.text; using iTextSharp.text.pdf; using Zen.Barcode; // 1. 用Zen Barcode生成二维码的System.Drawing.Image CodeQrBarcodeDraw qrCode = BarcodeDrawFactory.CodeQr; System.Drawing.Image qrSystemImage = qrCode.Draw("12245654", 50); // 2. 将System.Drawing.Image转换为内存流(用PNG格式保证二维码清晰度) using (MemoryStream ms = new MemoryStream()) { qrSystemImage.Save(ms, ImageFormat.Png); ms.Position = 0; // 重置流的读取位置到开头 // 3. 创建iTextSharp兼容的Image对象 Image qrITextImage = Image.GetInstance(ms); // 4. 把二维码添加到PDF文档中(完整的PDF生成示例) using (FileStream fs = new FileStream("带二维码的文档.pdf", FileMode.Create)) { Document pdfDoc = new Document(); PdfWriter.GetInstance(pdfDoc, fs); pdfDoc.Open(); // 可以调整二维码的位置、大小,比如设置缩放比例 qrITextImage.ScaleToFit(100, 100); pdfDoc.Add(qrITextImage); pdfDoc.Close(); } } // 释放System.Drawing.Image的资源 qrSystemImage.Dispose();
关键说明
- 跳过PictureBox:PictureBox是WinForms的UI控件,用来展示图片的,在这里完全是多余的中间环节,直接用Zen Barcode的
Draw方法返回的System.Drawing.Image即可,节省内存和代码复杂度。 - 流转换的必要性:iTextSharp的
Image.GetInstance方法支持从流、字节数组或文件路径创建图片,我们通过MemoryStream把System.Drawing的图片转换成流,就能被iTextSharp识别。 - 资源管理:一定要用
using语句处理流对象(MemoryStream、FileStream),它们会自动释放资源;手动调用Dispose()释放System.Drawing.Image,避免内存泄漏。
如果你非要用PictureBox里的图片,只需要把上面的qrSystemImage替换成picQRImage.Image就行,但还是建议直接用Zen的返回值,更高效。
内容的提问来源于stack exchange,提问作者jaltami
相关产品推荐
相关产品推荐

