C# PdfContentByte.SetFontAndSize()抛出;对象引用未设置为对象的实例;
我正在尝试添加一个文本框批注,其文本具有指定的字体和大小。代码如下:C# PdfContentByte.SetFontAndSize()抛出;对象引用未设置为对象的实例;,c#,pdf,itextsharp,itext,C#,Pdf,Itextsharp,Itext,我正在尝试添加一个文本框批注,其文本具有指定的字体和大小。代码如下: void addTextBox(string inputPath,string outputPath) { PdfReader pdfReader = new PdfReader(inputPath); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create)); PdfCo
void addTextBox(string inputPath,string outputPath)
{
PdfReader pdfReader = new PdfReader(inputPath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));
PdfContentByte pcb = new PdfContentByte(pdfStamper.Writer);
BaseFont baseFont = FontFactory.GetFont(FontFactory.HELVETICA).BaseFont;
float fontsize = 32;
pcb.SetFontAndSize(baseFont, fontsize);
PdfAnnotation textbox = PdfAnnotation.CreateFreeText(pdfStamper.Writer, new iTextSharp.text.Rectangle(200, 200, 3000, 3000), "Here is a Textbox", pcb);
pdfStamper.AddAnnotation(textbox, 1);
pdfStamper.Close();
}
pcb.SetFontAndSize()
调用引发异常:
Object reference not set to an instance of an object.
发生此错误时,
pcb
已实例化,并且fontsize
已成功分配其数值,因此此处未分配的对象是什么?将PdfContentByte(pdfStamper.Writer)
替换为pdfStamper.GetOverContent(1)
问题就会消失。我不习惯看到新的PdfContentByte(pdfStamper.Writer)
。您是否尝试过创建PdfContentByte
的标准方法?这是pdfStamper.GetOverContent(1)?我也不习惯看到FontFactory.GetFont(FontFactory.HELVETICA.BaseFont
)。您确定他的值不是空的吗?为什么不使用BaseFont.CreateFont()
方法创建BaseFont
?@BrunoLowagie将PdfContentByte
赋值更改为pdfStamper.GetOverContent(1)
解决了这个问题;如果你把答案贴出来,我会接受的。FontFactory.GetFont(FontFactory.HELVETICA).BaseFont的值肯定不是null
,我在抛出异常时检查了变量的值。