I am using iText 7 for C#, or actually I am migrating from iTextSharp 5 to iText 7. In iTextSharp, I have used IPdfPageEvent
(more specifically the PdfPageEventHelper
helper class) to add a watermark to PDF:
public MyPageEvent extends PdfPageEventHelper {
private Image waterMark;
public MyPageEvent(Image img) {
waterMark = img;
}
public void OnEndPage(PdfWriter writer, Document doc) {
PdfContentByte content = writer.GetUnderContent();
content.AddImage(waterMark);
}
}
Image watermarkImage = new Image(imgPath);
watermarkImage.setAbsolutePosition(x, y);
writer.setPageEvent( new MyPageEvent(watermarkImage) );
Now that i am looking for iText 7 equivalent for that. I can't find the IPageEvent
interface, nor classes such as PdfPageEventHelper
in iText 7 for C#.
Please take a look at Chapter 7: Handling events; setting viewer preferences and writer properties where the event system is explained.
In this chapter, we explain how to use the
addEventHandler()
method for the following events:START_PAGE
– triggered when a new page is started,END_PAGE
– triggered right before a new page is started,INSERT_PAGE
– triggered when a page is inserted, andREMOVE_PAGE
– triggered when a page is removed.In iText 5, it was necessary to add a watermark in the
OnEndPage()
method. In iText 7, you can choose for theSTART_PAGE
orEND_PAGE
event.Suppose that you want to add an image as a watermark. In that case, you'd create an implementation of the
IEventHandler
interface like this:There's also an example where we add text instead of an image. More specifically the a header:
Using such an
IEventHandler
implementation is easy:As you can see, you can simply add the event handler to the
PdfDocument
specifying for which event the handler has to be triggered.Important: the code I shared is Java code, but the same classes, interfaces and methods exist in C#, so it shouldn't be a problem for you to adapt my examples.