PdfContentByte.SetFontAndSize()抛出“对象引用未设置为对象的实例”

时间:2016-04-21 00:19:49

标签: 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));
    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已成功分配其数值,那么这里的未分配对象是什么?

1 个答案:

答案 0 :(得分:3)

Replace PdfContentByte(pdfStamper.Writer) with pdfStamper.GetOverContent(1) and the problem will disappear.