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
,我在抛出异常时检查了变量的值。