Adding an internal anchor reference using ShowTextAligned causes a null reference exception

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Adding an internal anchor reference using ShowTextAligned causes a null reference exception

paulsachs
I am adding an anchor to a canvas. The canvas is the 'over content' for a single page in a PDFStamper object. The anchor is an internal reference to a name on another page.

When I use ColumnText.ShowTextAligned to add the anchor I am getting a 'Object reference not set to an instance of an object' error. Is it because the canvas does not contain the target reference? If so, what can I do?

Here is a working example of the problem:

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

    var ms = new MemoryStream();
    var document = new iTextSharp.text.Document();

    // Create a simple two page PDF document:
    var pdfWriter = PdfWriter.GetInstance(document, ms);
    pdfWriter.InitialLeading = 40F;
    document.Open();
    document.Add(new Phrase("Simple Phrase on Page 1"));
    document.NewPage();
    document.Add(new Phrase("Simple Phrase on Page 2"));
    document.Close();

    // Read the 2 page document, create a stamper and add two anchors
    // at absolute positions on page 1.
    var pdfReader = new PdfReader(ms.ToArray());
    var ms2 = new MemoryStream();
    var pdfStamper = new PdfStamper(pdfReader, ms2);
    var canvas = pdfStamper.GetOverContent(1);

    // add an external anchor
    var anchor1 = new Anchor("External Anchor");
    anchor1.Reference = "www.stackoverflow.com";
    ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, anchor1, 100, 200, 0);

    // add an internal anchor
    var anchor2 = new Anchor("Internal Anchor");
    anchor2.Reference = "#abc";

    // this next line causes a null reference exception - why?
    ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, anchor2, 100, 100, 0);

    pdfStamper.Close();
Loading...