Click here to Skip to main content
6,594,932 members and growing! (15,921 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate License: The GNU Lesser General Public License

E-signing PDF documents with iTextSharp

By Alaa-eddine KADDOURI

an example demonstrating how to sign PDF documents with iTextSharp library
C#, .NET, WinXP, ASP.NET, Visual Studio, Dev
Posted:17 Jun 2006
Views:122,044
Bookmarked:64 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
16 votes for this article.
Popularity: 4.97 Rating: 4.13 out of 5
1 vote, 6.3%
1
2 votes, 12.5%
2

3
3 votes, 18.8%
4
10 votes, 62.5%
5

Sample Image - Esignature.jpg

Introduction

In this article I will present a simple source code allowing you to digitally sign a PDF document and modify its Meta data. I will use the excellent and free port of iText library : iTextSharp that can be downloaded here.
You'll need Visual Studio 2005 to be able to open and build the project

If you don�t know what are digital signatures or how does they work, you can go here or here or simply ask Google :)

iTextSharp provides a lot of interesting features to create and manipulate PDF documents, but in this article we will only use digital signature functions.
I will also use some function to manipulate pkcs#12 certificates, the only thing you need to know here is that our digital signature will use a private key extracted from a pkcs#12 certificate.

Getting started

So the first thing you have to do is to install a certificate on your browser, if you don�t have one you can install demo certificate from here.
Then extract the pkcs#12 certificate as described bellow :

  • Open Internet explorer and click on tools then internet options
  • Go to 'content' tab and click 'certificats'
  • Choose a certificate from the list and click Export
  • Follow the wizard and when asked choos to include private key with extracted certificate
  • Enter a password when prompted (dont give an empty one!!!)

You are now ready to use the code provided in this article.
Using the signature example:
1 � compile and run the example
2 � browse to the PDF source file you want to sign
3 � browse and choose a destination pdf file
4 � add/modify the PDF meta data if you want
5 � browse to the certificate (the .pfx file) you just extracted and choose it
6 � give the password you used to extract the certificate
5 � add signature information if needed (reason, contact and location)
6 � click sign button
In the debug box you�ll see operaion�s progress
If everything goes well open your explorer and browse to location you entered for Target file, open this file with Adobe Acrobat reader, your document is signed! =)

Now how all this work?

In the source code provided with this article, I wrote library called PDFSigner, it�s a helper package that use iTextSharp and do everything you need for digital signatures.
It contains three classes

  • Cert class: this class is used to hold a certificate and extract needed information for signature, the most important methode in this class is processCert (will be explained bellow)
  • MetaData class : holds PDF meta data
  • PDFSigner class : the construction of this class takes a Cert object and if needed a MetaData object, the most important methode here is the sign methode (will be explained bellow)

  • processCet method

            private void processCert()
            {
                    string alias = null;                                                
                    PKCS12Store pk12;
    
                    //First we'll read the certificate file
    
                    pk12 = new PKCS12Store(new FileStream(this.Path, FileMode.Open, FileAccess.Read), this.password.ToCharArray());
    
                    //then Iterate throught certificate entries to find the private key entry
    
                    IEnumerator i = pk12.aliases();
                    while (i.MoveNext())
                    {
                        alias = ((string)i.Current);
                        if (pk12.isKeyEntry(alias))
                            break;
                    }
    
                    this.akp = pk12.getKey(alias).getKey();
                    X509CertificateEntry[] ce = pk12.getCertificateChain(alias);
                    this.chain = new org.bouncycastle.x509.X509Certificate[ce.Length];
                    for (int k = 0; k < ce.Length; ++k)
                        chain[k] = ce[k].getCertificate();
    
                }
    
    
    This methode reads the certificate and iterate throught its entries to find the private key entry then extract it.
    it also construct the certificate's chain if available

    sign method

            public void Sign(string SigReason, string SigContact, string SigLocation, bool visible)
            {
                PdfReader reader = new PdfReader(this.inputPDF);
                //Activate MultiSignatures
    
                PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);
                //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
    
                //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0'); 
    
    
                st.MoreInfo = this.metadata.getMetaData();
                st.XmpMetadata = this.metadata.getStreamedMetaData();
                PdfSignatureAppearance sap = st.SignatureAppearance;
                
                sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
                sap.Reason = SigReason;
                sap.Contact = SigContact;
                sap.Location = SigLocation;            
                if (visible)
                    sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
                
                st.Close();
            }
    
    this function reads the content of a given pdf , then it use the read data to create a new PDF using PDFStamper.
    PDFStamper is a PDF Writer that can sign PDF documents, the signature appearence can be configured so you can add a reason, a contact and a location attributes to the signature.
    SetCrypto methode allows us to sign the document using the private key and chain certificate we extracted from the certificate file.
    And finally, the SetVisibleSignature is used if you need to add a visible signature to the document

    PDFReader, PDFStamper and PdfSignatureAppearance are provided by iTextSharp library

    Well, that�s all for now :) I hope that you found my first article useful � if you have any question or have any problem to build/run this example don�t hesitate to post a comment.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License

About the Author

Alaa-eddine KADDOURI


Member

Occupation: Software Developer
Location: France France

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 127 (Total in Forum: 127) (Refresh)FirstPrevNext
GeneralOrg.BouncyCastle.Crypto.AsymmetricKeyParameter exist in itextsharp.dll Pinmemberta00720:20 29 Sep '09  
GeneralRe: Org.BouncyCastle.Crypto.AsymmetricKeyParameter exist in itextsharp.dll PinmemberAlaa-eddine KADDOURI23:09 29 Sep '09  
GeneralRe: Org.BouncyCastle.Crypto.AsymmetricKeyParameter exist in itextsharp.dll Pinmemberta0071:41 30 Sep '09  
Generalsign pdf's using timestamps from verisign PinmemberMember 21913515:22 14 Sep '09  
GeneralRe: sign pdf's using timestamps from verisign PinmemberAlaa-eddine KADDOURI6:10 14 Sep '09  
GeneralRe: sign pdf's using timestamps from verisign PinmemberMember 21913516:11 14 Sep '09  
Answerpk12.getCertificateChain(alias) == null problem Pinmemberantiacid6:05 26 Aug '09  
Generalwhat version of the iTextSharp.dll Pinmemberju168185:10 2 Jul '09  
GeneralWindows service Error [modified] PinmemberYekbunn1:11 25 Jun '09  
GeneralRegarding signing pdf with itextsharp PinmemberAnil Vijay Singh1:17 17 Jun '09  
GeneralUsing pkcs#11 to allow SmartCard auth Pinmembernarva22:28 10 Jun '09  
AnswerAny way to use HttpClientCertificate ? PinmemberJJC_782:52 13 May '09  
Generalhow can I add a timestamp? Pinmemberjaviovi20036:54 6 May '09  
GeneralRe: how can I add a timestamp? PinmemberMember 446982621:00 9 Jun '09  
GeneralRe: how can I add a timestamp? PinmemberAlaa-eddine KADDOURI23:53 9 Jun '09  
QuestionASP .NET Compatible? PinmemberJJC_7822:45 28 Apr '09  
AnswerRe: ASP .NET Compatible? PinmemberJJC_780:07 29 Apr '09  
QuestionSign Multiple Pages of PDF [modified] Pinmembershaqil2:21 11 Apr '09  
QuestionSignature position PinmemberDaniel Kamisnki7:00 7 Apr '09  
GeneralPDF/A compatible? Pinmemberperformis5:26 26 Mar '09  
GeneralRe: PDF/A compatible? PinmemberAlaa-eddine KADDOURI6:53 26 Mar '09  
GeneralRe: PDF/A compatible? Pinmemberperformis7:01 26 Mar '09  
GeneralRe: PDF/A compatible? PinmemberAlaa-eddine KADDOURI7:28 26 Mar '09  
GeneralExample in VB PinmemberUgoMontefiori4:11 16 Feb '09  
GeneralRequest: already compiled code ready to use PinmemberBilou_Gateux1:16 15 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Jun 2006
Editor:
Copyright 2006 by Alaa-eddine KADDOURI
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project