iTextSharp–Add watermark to PDF
public class PdfWriterEvents : IPdfPageEvent { string watermarkText = string.Empty; public PdfWriterEvents(string watermark) { watermarkText = watermark; } public void OnStartPage(PdfWriter writer, Document document) { float fontSize = 80; float xPosition = iTextSharp.text.PageSize.A4.Width / 2; float yPosition = (iTextSharp.text.PageSize.A4.Height - 140f) / 2; float angle = 45; try { PdfContentByte under = writer.DirectContentUnder; BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); under.BeginText(); under.SetColorFill(BaseColor.LIGHT_GRAY); under.SetFontAndSize(baseFont, fontSize); under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle); under.EndText(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } public void OnEndPage(PdfWriter writer, Document document) { } public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { } public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { } public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { } public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { } public void OnOpenDocument(PdfWriter writer, Document document) { } public void OnCloseDocument(PdfWriter writer, Document document) { } }
Now we can use this class in pdf building Class~ following way to show watermark on your pdf document
using (MemoryStream msReport = new MemoryStream()) { //WaterMark PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfWriter.PageEvent = new PdfWriterEvents("Demo Document"); pdfDoc.Open(); //Adding Image pdfDoc.Add(jpg); //Adding heading pdfDoc.Add(heading); //Adding heading Description pdfDoc.Add(headingdesc); //Adding Table pdfDoc.Add(table); pdfDoc.Add(employeeSignature); pdfDoc.Add(employeeSignaturePart2); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); } }
The Follwing is How it Looks after adding watermark
iTextSharp–Add watermark to PDF
Reviewed by Rejeti Praveen Kumar
on
03:51
Rating:

nice
ReplyDeleteThanks Mr.Srikanth
ReplyDeleteAdd watermark to PDF, recommend to use iDiTect.PDF, less code in C#, easier to use, full details here
ReplyDelete