Adding an Image Watermark to a Pdf When Creating It Using iTextSharp

I wonder if this is possible. I saw a lot of messages about adding a watermark after the PDF was created and saved to disk. But at the time of creating the document, how to add an image watermark. I know how to add an image to a document. But how can I position it so that it gets to the end of the page.

+6
source share
2 answers

This is essentially identical to adding a header or footer.

You need to create a class that implements PdfPageEvent , and in OnPageEnd , grab the PdfContentByte page and draw an image. Use absolute position.

Note. You probably want to extract from PdfPageEventHelper, it has empty implementations of all the page events, so you just need to write the method that you really need.

Note. If your image is mostly transparent, drawing it on top of your page will cover many things. IIRC ("If I Return Right"), PNG and GIF files added by iText will automatically be masked appropriately, allowing things to display beneath them.

If you want to add an opaque image to everything, you should replace OnStartPage() instead.

This is Java, but conversion is basically a matter of using the method name and exchanging get / set calls to access the properties.

 Image watermarkImage = new Image(imgPath); watermarkImage.setAbsolutePosition(x, y); writer.setPageEvent( new MyPageEvent(watermarkImage) ); public MyPageEvent extends PdfPageEventHelper { private Image waterMark; public MyPageEvent(Image img) { waterMark = img; } public void OnEndPage/*OnStartPage*/(PdfWriter writer, Document doc) { PdfContentByte content = writer.getContent(); content.addImage( waterMark ); } } 
+4
source

For C # use this code ...

 //new Document Document DOC = new Document(); // open Document DOC.Open(); //create New FileStream with image "WM.JPG" FileStream fs1 = new FileStream("WM.JPG", FileMode.Open); iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs1), ImageFormat.Jpeg); //Scale image JPG.ScalePercent(35f); //Set position JPG.SetAbsolutePosition(130f,240f); //Close Stream fs1.Close(); DOC.Add(JPG); 
+4
source

Source: https://habr.com/ru/post/888393/


All Articles