Add Digital Signature to a PDF programmatically using iTextSharp and Microsoft .NET

  • Post author:
  • Post category:Blog
  • Post comments:0 Comments
  • Reading time:2 mins read

You must to prepare bellow things:

– iTextSharp library

– Valid Certificate file (.pfx). It means the .pfx file not yet expired

Use these guides to add digital signature to  a pdf file using iTextSharp

1. Add using statement

using iTextSharp.text;
using iTextSharp.text.pdf;
using Org.BouncyCastle.Pkcs;
using System.IO;
using System.Collections;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509;

2. Add a Sign method

public static void Sign(string certPath, string certPassword,
            string pdfPath, string outPath,
            string reason, string location)
		string alias = null;
		Pkcs12Store pk12 = new Pkcs12Store(new FileStream(certPath,
		FileMode.Open, FileAccess.Read), certPassword.ToCharArray());
		IEnumerator i = pk12.Aliases.GetEnumerator();
		while (i.MoveNext())
			alias = ((string)i.Current);
			if (pk12.IsKeyEntry(alias))
		AsymmetricKeyParameter akp = pk12.GetKey(alias).Key;
		X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
		X509Certificate[] chain = new X509Certificate[ce.Length];
		for (int k = 0; k < ce.Length; ++k)
			chain[k] = ce[k].Certificate;
		PdfReader reader = new PdfReader(pdfPath);
		PdfStamper st = PdfStamper.CreateSignature(reader, new
		FileStream(outPath, FileMode.Create, FileAccess.Write), '\0');
		PdfSignatureAppearance sap = st.SignatureAppearance;
		sap.SetCrypto(akp, chain, null, PdfSignatureAppearance.WINCER_SIGNED);                       
		sap.Reason = reason;            
		sap.Location = location;
		//use this line to render signature like PDF Professional do
		sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; //optional
		sap.SetVisibleSignature(new iTextSharp.text.Rectangle(50, 75, 300, 150), 1, null);

Hope this help

Leave a Reply