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

升级iTextSharp至5.0.0后cb.AddTemplate调用报错的技术咨询

解决iTextSharp 5.0.0中cb.AddTemplate报错的问题

我之前用iTextSharp 2.0.0写了一段给PDF插入文本的代码,运行完全正常:

string fileName = "test.pdf"; 
string oldFile = System.Web.Hosting.HostingEnvironment.MapPath("~/AuthDoc/CoverPage.pdf"); 
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName); 

// open the reader 
PdfReader reader = new PdfReader(oldFile); 
Rectangle size = reader.GetPageSizeWithRotation(1); 
Document document = new Document(size); 

// open the writer 
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); 
PdfWriter writer = PdfWriter.GetInstance(document, fs); 
document.Open(); 

// the pdf content 
PdfContentByte cb = writer.DirectContent; 

// select the font properties 
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
cb.SetColorFill(BaseColor.DARK_GRAY); 
cb.SetFontAndSize(bf, 8); 

string text = ""; 
cb.BeginText(); 
text = "Hitesh"; 
cb.ShowTextAligned(1, text,500,500, 0); 
cb.EndText(); 

PdfImportedPage page = writer.GetImportedPage(reader, 1); 
cb.AddTemplate( page, 0, 0); 

document.Close(); 
fs.Close(); 
writer.Close(); 
reader.Close(); 

byte[] bytes = System.IO.File.ReadAllBytes(newFile); 
return bytes;

但升级到iTextSharp 5.0.0之后,cb.AddTemplate(page, 0, 0)这行突然报错,错误信息是:

'The type 'Matrix' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'

问题原因

iTextSharp 5.0.0开始对依赖的处理有变化,AddTemplate方法在新版本中需要依赖System.Drawing程序集里的Matrix类型,而旧版本(2.0.0)可能内部处理了这个依赖,不需要显式引用。

解决步骤

  • 步骤1:添加System.Drawing程序集引用
    在你的项目中,右键点击「引用」→「添加引用」,在.NET程序集列表里找到System.Drawing(版本匹配提示里的2.0.0.0,或者兼容的更高版本比如4.0.0.0也可以正常工作),勾选后确认添加。

  • 步骤2:检查命名空间(可选)
    如果添加引用后仍然有问题,可以在代码文件顶部添加命名空间引用:

    using System.Drawing;
    
  • 步骤3:替换AddTemplate调用(备选方案)
    如果不想添加System.Drawing引用,也可以改用AddTemplate的另一个重载方法,传入数值参数构造矩阵效果,和原代码功能一致:

    // 参数对应矩阵的a,b,c,d,e,f,这里实现和原代码相同的页面平移效果
    cb.AddTemplate(page, 1, 0, 0, 1, 0, 0);
    

    这个重载不需要依赖System.Drawing的Matrix类型,直接用数值参数就能完成页面导入。

验证

完成上述操作后,重新编译运行代码,cb.AddTemplate的报错应该就会消失,PDF插入文本的功能可以正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:32:25