Use Itextsharp component to add image watermark to PDF document, text watermark

Source: Internet
Author: User

Recently in doing a PDF document add Watermark function, toss a long time, finally good. Make a note of the following:

First will use the ITEXTSHARP components, we can go to the official website to download, at the same time I will be attached in this article.

The code adds a reference to:
Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;  Using iTextSharp.text.pdf;  Using System.IO;  Using
Create a PDF that displays the specified picture
<summary>///Create a PDF showing the specified picture///</summary>//<param name= "Picpdfpath" ></p aram>//<param name= "Picpath" ></param>///<returns></returns> Public St atic bool Createpdfbypic (string picpdfpath,string picpath) {//Create a new document doc = new DOCU            ment (); try {//Create a writer (writer) associated with the Document Object Pdfwriter.getinstance (Doc, New FileStream (pi                Cpdfpath, FileMode.Create, FileAccess.ReadWrite)); Open a document Doc.                Open ();                Add content to the document Image img = image.getinstance (picpath); Img.                SetAbsolutePosition (); Doc.                Add (IMG);            return true;                } catch (Exception ex) {return false;            Throw ex;    } finally {if (doc! = null) {                Doc.                Close (); }            }         }

Add a picture watermark to a PDF document

<summary>//Plus picture watermark///</summary>//<param name= "Inputfilepath" &GT;&LT;/PARAM&G        T <param name= "Outputfilepath" ></param>//<param name= "Modelpicname" ></param>// /<param name= "top" ></param>//<param name= "left" ></param>//<returns>< /returns> public static bool Pdfwatermark (string Inputfilepath, String Outputfilepath, String modelpicname, Floa            T top, float left) {//throw new notimplementedexception ();            Pdfreader pdfreader = null;            Pdfstamper pdfstamper = null;                 try {pdfreader = new Pdfreader (Inputfilepath);                 int numberofpages = pdfreader.numberofpages;                 ITextSharp.text.Rectangle psize = pdfreader.getpagesize (1); Float width = psize.                 Width; float height = psize.                 Height; Pdfstamper = new PDfstamper (Pdfreader, New FileStream (Outputfilepath, FileMode.Create));                 Pdfcontentbyte watermarkcontent;                 ITextSharp.text.Image Image = iTextSharp.text.Image.GetInstance (modelpicname); Image. Grayfill = 20;//transparency, gray fill//image. rotation//rotating//image. rotationdegrees//rotation angle//watermark position if (left < 0) {left = W IDTH/2-image.                Width + left; }//image. SetAbsolutePosition (left, (height-image).                Height)-top); Image. SetAbsolutePosition (left, (HEIGHT/2-image).                  Height)-top); Watermark per page, you can also set a page watermark for (int i = 1; I <= numberofpages; i++) {//wat Ermarkcontent = Pdfstamper.getundercontent (i);//content lower watermark Watermarkcontent = pdfstamper.getovercontent (i)                ;//Content Upper Watermark watermarkcontent.addimage (image);      }          STRMSG = "Success";            return true;                             } catch (Exception ex) {throw ex;                 } finally {if (pdfstamper! = null) pdfstamper.close ();            if (Pdfreader! = null) pdfreader.close (); }        }

Add normal deflection angle text watermark

<summary>////Add normal deflection angle text watermark///</summary>//<param name= "Inputfilepath" ></ param>//<param name= "Outputfilepath" ></param>//<param name= "Watermarkname" ></p aram>//<param name= "permission" ></param> public static void Setwatermark (String inputfilep            Ath, String outputfilepath,string watermarkname) {Pdfreader pdfreader = null; Pdfstamper pdfstamper = null;
Gets the used right pdfreader.unethicalreading = true; try {pdfreader = new Pdfreader (Inputfilepath); Pdfstamper = new Pdfstamper (Pdfreader, New FileStream (Outputfilepath, FileMode.Create)); int total = pdfreader.numberofpages + 1; ITextSharp.text.Rectangle psize = pdfreader.getpagesize (1); Float width = psize. Width; float height = psize. Height; Pdfcontentbyte 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 = Pdfstamper.getovercontent (i);//watermark above content Content = Pdfstamper.getundercontent (i);//Add watermark below contents//Transparency GS. fillopacity = 0.3f; Content. Setgstate (GS); Content. Setgrayfill (0.3f); Begins writing to the text content. Begintext (); Content. Setcolorfill (Basecolor.light_gray); Content. Setfontandsize (font, 100); Content. Settextmatrix (0, 0); Content. Showtextaligned (Element.align_center, Watermarkname, WIDTH/2-50,HEIGHT/2-50, 55); Content. Setcolorfill (Basecolor.black); Content. Setfontandsize (font, 8); Content. Showtextaligned (Element.align_center, watermarkname, 0, 0, 0); Content. Endtext (); }}catch (Exception ex) {throw ex; } finally {if (pdfstamper! = null) pdfstamper.close (); if (Pdfreader! = null) pdfreader.close (); } }

Add an oblique watermark

<summary>///Add tilt watermark////</summary>//<param name= "Inputfilepath" ></param&        Gt <param name= "Outputfilepath" ></param>//<param name= "Watermarkname" ></param>/ <param name= "UserPassword" ></param>//<param name= "OwnerPassword" ></param>// <param name= "permission" ></param> public static void Setwatermark (String inputfilepath, String Outputfi Lepath, String watermarkname, String UserPassword, string ownerpassword, int permission) {Pdfreader PDF            Reader = null;            Pdfstamper pdfstamper = null;                try {pdfreader = new Pdfreader (Inputfilepath);                Pdfstamper = new Pdfstamper (Pdfreader, New FileStream (Outputfilepath, FileMode.Create));                  Set Password//pdfstamper.setencryption (False,userpassword, OwnerPassword, permission); INT Total = pdfreader.numberofpages + 1;                Pdfcontentbyte content; Basefont font = Basefont.createfont (@ "C:\WINDOWS\Fonts\SIMFANG.                TTF ", Basefont.identity_h, basefont.embedded);                Pdfgstate GS = new Pdfgstate (); Gs.                fillopacity = 0.2f;//transparency Int j = Watermarkname.length;                char c;                int rise = 0;                    for (int i = 1; i < total; i++) {rise = 500;                                         Content = Pdfstamper.getovercontent (i);//watermark above contents//content = Pdfstamper.getundercontent (i);//Add watermark underneath content Content.                    Begintext (); Content.                    Setcolorfill (Basecolor.dark_gray); Content.                    Setfontandsize (font, 50); Set Watermark text font tilt start if (j >=) {content.                        Settextmatrix (200, 120); for (int k = 0; K < J k++) {content.                            Settextrise (Rise);                            c = Watermarkname[k]; Content.                            Showtext (c + "");                        Rise-= 20; }} else {content.                        Settextmatrix (180, 100); for (int k = 0; k < J; k++) {content.                            Settextrise (Rise);                            c = Watermarkname[k]; Content.                            Showtext (c + "");                        Rise-= 18; }}//font settings end content.                    Endtext (); Draw a round//content.                    Ellipse (250, 450, 350, 550); Content.                    Setlinewidth (1f); Content.                 Stroke (); }} catch (Exception ex) {throw ex;                 } finally {if (pdfstamper! = null) pdfstamper.close ();            if (Pdfreader! = null) pdfreader.close (); }        }

Examples of calling methods:

String path = "D://my.pdf";               Htmltopdfutil.htmltopdf (Request.Url.AbsoluteUri, path);               Htmltopdfutil.htmltopdf (sburllist.tostring (), path);               Pdfsetwatermark.pdfwatermark (Path, "D://my.pdf", Server.MapPath ("/htmltopdf/tools/sy.bmp"), 0, 0);               Pdfsetwatermark.setwatermark ("D://my.pdf", "D://my2.pdf", "TEST");               Pdfsetwatermark.setwatermark ("D://my.pdf", "D://my2.pdf", "TEST", "", "", 1);

Use Itextsharp component to add image watermark to PDF document, text watermark

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.