sigil
sigil

Reputation: 9546

PdfContentByte.SetFontAndSize() throws "Object reference not set to instance of object"

I'm trying to add a text box annotation whose text has a specified font and size. Code as follows:

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();
}

The pcb.SetFontAndSize() call is throwing an exception:

Object reference not set to an instance of an object.

pcb has been instantiated by the time this error occurs, and fontsize has been successfully assigned its numerical value, so what's the unassigned object here?

Upvotes: 2

Views: 1036

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

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

Upvotes: 3

Related Questions