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

如何在iTextSharp中使用Bitmap图片?添加时遇错求解决

解决Bitmap添加到PDF时的错误

几个靠谱的排查方向

  • 别直接用文件Bitmap,转成内存流再处理
    很多时候错误是因为Bitmap文件被锁定,或者PDF库读取本地文件时遇到权限/占用问题。把Bitmap转成内存流再生成PDF可用的图片对象,示例(以iTextSharp为例):

    using (var barcodeBmp = GenerateYourBarcodeBitmap())
    using (var ms = new MemoryStream())
    {
        barcodeBmp.Save(ms, ImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);
        var pdfImg = iTextSharp.text.Image.GetInstance(ms);
        // 把pdfImg加到你的PDF文档里
        yourPdfDocument.Add(pdfImg);
    }
    
  • 检查Bitmap的像素格式
    有些PDF库不支持索引色、8位这类特殊像素格式的Bitmap,转成32位ARGB格式再试:

    using (var compatibleBmp = new Bitmap(barcodeBmp.Width, barcodeBmp.Height, PixelFormat.Format32bppArgb))
    {
        using (var g = Graphics.FromImage(compatibleBmp))
        {
            g.DrawImage(barcodeBmp, new Rectangle(0, 0, compatibleBmp.Width, compatibleBmp.Height));
        }
        // 用compatibleBmp去生成PDF图片
    }
    
  • 确认PDF库的使用姿势
    比如用iTextSharp的话,别直接把System.Drawing.Bitmap塞给Add方法,必须用Image.GetInstance转成库自己的Image对象。如果是其他库(比如PdfSharp),也要对应使用库提供的图片加载方法,别跨类型直接调用。

  • 排查内存问题
    如果条码Bitmap尺寸超大,容易触发内存溢出,试着降低条码的分辨率或者缩小尺寸再生成。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:18