0
votes

I am trying to follow some of the iText7 documentation to insert a header onto my pdf document however GetPageSize() returns 'Object reference not set to an instance of an object.'.

I've tried adding pages through both the PdfDocument object and the Document object and setting the page size. I can see 4 pages in the loop however nothing I change will give me a page size.

public static void createPdf(string dest)
        {
            MemoryStream stream = new MemoryStream();
            PdfWriter writer = new PdfWriter(stream);
            PdfDocument pdfDoc = new PdfDocument(writer);
            pdfDoc.AddNewPage(PageSize.A4);
            pdfDoc.AddNewPage(PageSize.A4);
            pdfDoc.AddNewPage(PageSize.A4);
            pdfDoc.AddNewPage(PageSize.A4);
            var doc = new Document(pdfDoc);

            doc.Add(new Paragraph("This is page 1."));
            doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            doc.Add(new Paragraph("This is page 2."));
            doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            doc.Add(new Paragraph("This is page 3."));
            doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            doc.Add(new Paragraph("This is page 4."));

            Paragraph header = (new Paragraph("Copy").SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA)).SetFontSize(14));

            for (int i = 1; (i <= pdfDoc.GetNumberOfPages()); i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                Rectangle pageSize = page.GetPageSize();
                float x = (pdfDoc.GetPage(i).GetPageSize().GetWidth() / 2);
                float y = (pdfDoc.GetPage(i).GetPageSize().GetTop() - 20);
                doc.ShowTextAligned(header, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
            }

            doc.Close();
        }

The error message System.NullReferenceException: 'Object reference not set to an instance of an object.' occurson the line Rectangle pageSize = page.GetPageSize();

1

1 Answers

1
votes

As soon as you use Document instance, it will flush the content written to PDF by default and thus as you have added 4 pages of content, the first one is already flushed when you come to executing your loop getting the rectangle sizes.

To fix this problem you can tell Document to not flush its content by default by passing false to the third parameter in the constructor (immediateFlush):

var doc = new Document(pdfDoc, PageSize.Default, false);