Search code examples
eventsitextpdf-writer

iTextSharp : Cannot attach PageEvent on a PdfSmartCopy writer


This code using ItextSharp 5.5.10:

 var msOutput = new MemoryStream();
 var document = new Document(PageSize.A4, 0, 0, 0, 20);
 var writer = new PdfSmartCopy(document, msOutput);
 writer.PageEvent = new MyHeaderFooterEvents();

Throws "Operation is not valid due to the current state of the object." when assigning the "writer.PageEvent" (also fails when doing a parameterless new Document()).

When this code works perfectly:

 var outputStream = new MemoryStream();
 var document = new Document(PageSize.A4, leftMargin, rightMargin, topMargin, bottomMargin);
 var writer = PdfWriter.GetInstance(document, outputStream);
 writer.PageEvent = new MyHeaderFooterEvents();

Any idea ?


Solution

  • The Pdf[Smart]Copy classes are intended for read-only usage. It's documented in the raw source code:

    /// Setting page events isn't possible with Pdf(Smart)Copy.
    /// Use the PageStamp class if you want to add content to copied pages.
    

    Note to the iText development team - if XML Documentation Comments using the <summary> tag are used instead of the current style, comments will show up in Visual Studio IntelliSense.