C # Use iTextSharp to add watermarks to PDF files,
Code:
/// <Summary> /// Add a normal deflection angle text watermark /// </summary> public static void SetWatermark (string filePath, string text) {PdfReader pdfReader = null; optional Stamper optional Stamper = null; string tempPath = Path. getDirectoryName (filePath) + Path. getFileNameWithoutExtension (filePath) + "_temptid"; try {pdfReader = new PdfReader (filePath); Specify Stamper = new specify Stamper (pdfReader, new FileStream (tempPath, FileMode. create); I Nt total = pdfReader. numberOfPages + 1; iTextSharp. text. rectangle psize = pdfReader. getPageSize (1); float width = psize. width; float height = psize. height; required contentbyte content; BaseFont font = BaseFont. createFont (@ "C: \ WINDOWS \ Fonts \ SIMFANG. TTF ", BaseFont. IDENTITY_H, BaseFont. EMBEDDED); PdfGState gs = new PdfGState (); for (int I = 1; I <total; I ++) {content = 1_stamper. getOverContent (I); // IN THE CONTENT Add watermark // content = watermark Stamper. getUnderContent (I); // Add a watermark to the bottom of the content // transparency gs. fillOpacity = 0.3f; content. setGState (gs); // content. setGrayFill (0.3f); // start to write the text content. beginText (); content. setColorFill (BaseColor. GRAY); content. setFontAndSize (font, 30); content. setTextMatrix (0, 0); content. showTextAligned (Element. ALIGN_CENTER, text, width-120, height-120,-45); // content. setColorFill (BaseColor. BLACK); // c Ontent. setFontAndSize (font, 8); // content. showTextAligned (Element. ALIGN_CENTER, waterMarkName, 0, 0, 0); content. endText () ;}} catch (Exception ex) {throw ex;} finally {if (except Stamper! = Null) Begin Stamper. Close (); if (pdfReader! = Null) pdfReader. Close (); System. IO. File. Copy (tempPath, filePath, true); System. IO. File. Delete (tempPath );}}View Code