Click here to Skip to main content
11,633,983 members (63,328 online)
Click here to Skip to main content

E-signing PDF documents with iTextSharp

, 17 Jun 2006 LGPL3 416K 9.7K 128
Rate this:
Please Sign up or sign in to vote.
An example demonstrating how to sign PDF documents with the iTextSharp library.

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 metadata. 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 digital signatures are or how they work, you can go here or here, or simply ask Google Smile | :)

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 the demo certificate from here. Then, extract the PKCS#12 certificate as described below:

  • Open Internet Explorer and click on Tools, then Internet Options.
  • Go to the 'Content' tab and click 'Certificates'.
  • Choose a certificate from the list and click Export.
  • Follow the wizard, and when asked, choose to include private key with the extracted certificate.
  • Enter a password when prompted (don't 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.
  7. Add signature information if needed (reason, contact, and location).
  8. Click the Sign button.

In the debug box, you’ll see the operation’s progress. If everything goes well, open your explorer and browse to the location you entered for the target file, open this file with Adobe Acrobat reader, and your document is signed! =).

Now, how will all this work?

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

  • Cert: this class is used to hold a certificate and extract the needed information for the signature; the most important method in this class is processCert (will be explained below).
  • MetaData: holds the PDF metadata.
  • PDFSigner: the construction of this class takes a Cert object and, if needed, a MetaData object. The most important method here is the Sign method (will be explained below).

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 method reads the certificate and iterates through its entries to find the private key entry, then extracts 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 uses the read data to create a new PDF using PDFStamper. PDFStamper is a PDF Writer that can sign PDF documents. The signature appearance can be configured so you can add a reason, a contact, and a location attribute to the signature. The SetCrypto method allows us to sign the document using the private key and chain certificate we extracted from the certificate file. And finally, SetVisibleSignature is used if you need to add a visible signature to the document. PDFReader, PDFStamper and PdfSignatureAppearance are provided by the iTextSharp library.

Well, that’s all for now Smile | :) I hope that you found my first article useful … If you have any questions or have any problems 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 (LGPLv3)

Share

About the Author

Alaa-eddine KADDOURI
Technical Lead
France France
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 3 Pin
Manoj Natarajan29-Apr-15 2:23
professionalManoj Natarajan29-Apr-15 2:23 
QuestionVerify the signature? Pin
Member 30546992-Mar-15 6:57
memberMember 30546992-Mar-15 6:57 
QuestionsetCrypto Pin
Dara Keon8-Jan-15 5:32
memberDara Keon8-Jan-15 5:32 
Bugsouci de l'auteur Pin
Member 1122180924-Nov-14 3:43
memberMember 1122180924-Nov-14 3:43 
Questioni get error stating that signature defined, must be closed within signatureappearance Pin
Member 107366893-Jun-14 7:27
memberMember 107366893-Jun-14 7:27 
AnswerRe: i get error stating that signature defined, must be closed within signatureappearance Pin
Ravindra Sadaphule9-Aug-14 22:15
memberRavindra Sadaphule9-Aug-14 22:15 
GeneralRe: i get error stating that signature defined, must be closed within signatureappearance Pin
Member 1073668912-Aug-14 4:33
memberMember 1073668912-Aug-14 4:33 
QuestionRevision label and picture as signature Pin
Rui Frazao26-Feb-14 0:18
memberRui Frazao26-Feb-14 0:18 
QuestionNot able to download source code since last 2 months using my credentials Pin
Member 104391409-Feb-14 2:34
memberMember 104391409-Feb-14 2:34 
QuestionCreate pfx file for domain users Pin
rilov10-Oct-13 10:59
memberrilov10-Oct-13 10:59 
GeneralThanks a lot Pin
Member 941865011-Sep-13 5:13
memberMember 941865011-Sep-13 5:13 
GeneralMy vote of 5 Pin
Rok Banko2-Sep-13 3:56
memberRok Banko2-Sep-13 3:56 
GeneralThanks man. Pin
Member 59097829-May-13 21:47
memberMember 59097829-May-13 21:47 
QuestionWhat to do when PKCS #12 cert is not available Pin
Harvey Flaisher27-Mar-13 13:08
memberHarvey Flaisher27-Mar-13 13:08 
Questionvb.net Pin
ewerton.4722-Feb-13 4:35
memberewerton.4722-Feb-13 4:35 
AnswerRe: vb.net Pin
Cajie6-Mar-13 7:34
memberCajie6-Mar-13 7:34 
QuestionRe: vb.net Pin
Member 1005027913-May-13 21:16
memberMember 1005027913-May-13 21:16 
QuestionThank you Pin
Kalpana Volety11-Jan-13 11:38
memberKalpana Volety11-Jan-13 11:38 
QuestionSignature not valid Pin
sodakdoogie12-Dec-12 5:42
membersodakdoogie12-Dec-12 5:42 
Hi,

I'm using your source files and the signature goes in fine, but when I open the file it says the signature isn't valid. Looks like you had someone else have this problem several years ago with a German version of Adobe. I'm using Adobe Acrobat X. Have you run into this problem with that version?
QuestionFantasic piece of code Pin
zaxbowow12-Oct-12 6:36
memberzaxbowow12-Oct-12 6:36 
QuestionProtected pdf with Password Pin
anismanoula2-Oct-12 5:33
memberanismanoula2-Oct-12 5:33 
AnswerRe: Protected pdf with Password Pin
Alaa-eddine KADDOURI11-Oct-12 3:01
memberAlaa-eddine KADDOURI11-Oct-12 3:01 
QuestionProblem with certificates Pin
MelechDavid5-Jul-12 5:33
memberMelechDavid5-Jul-12 5:33 
AnswerRe: Problem with certificates Pin
Alaa-eddine KADDOURI5-Jul-12 6:34
memberAlaa-eddine KADDOURI5-Jul-12 6:34 
GeneralRe: Problem with certificates Pin
MelechDavid5-Jul-12 22:37
memberMelechDavid5-Jul-12 22:37 
Questiongot NullReferenceException while trying sample code Pin
ai_mueller10-Sep-11 12:10
memberai_mueller10-Sep-11 12:10 
AnswerRe: got NullReferenceException while trying sample code Pin
Alaa-eddine KADDOURI10-Sep-11 12:16
memberAlaa-eddine KADDOURI10-Sep-11 12:16 
GeneralBut it does not hv an option to signa selected page Pin
Sujit Soni31-May-11 9:07
memberSujit Soni31-May-11 9:07 
GeneralRe: But it does not hv an option to signa selected page Pin
Alaa-eddine KADDOURI31-May-11 9:21
memberAlaa-eddine KADDOURI31-May-11 9:21 
GeneralCertificate Error Pin
elBaz24-Mar-11 8:34
memberelBaz24-Mar-11 8:34 
GeneralRe: Certificate Error Pin
elBaz24-Mar-11 8:56
memberelBaz24-Mar-11 8:56 
GeneralRe: Certificate Error Pin
Alaa-eddine KADDOURI24-Mar-11 9:56
memberAlaa-eddine KADDOURI24-Mar-11 9:56 
GeneralRe: Certificate Error Pin
elBaz24-Mar-11 12:17
memberelBaz24-Mar-11 12:17 
GeneralRe: Certificate Error Pin
Alaa-eddine KADDOURI24-Mar-11 13:13
memberAlaa-eddine KADDOURI24-Mar-11 13:13 
GeneralRe: Certificate Error Pin
elBaz24-Mar-11 16:06
memberelBaz24-Mar-11 16:06 
GeneralRe: Certificate Error Pin
Alaa-eddine KADDOURI25-Mar-11 3:43
memberAlaa-eddine KADDOURI25-Mar-11 3:43 
GeneralNew version of itextsharp Pin
Christatos2-Feb-11 22:40
memberChristatos2-Feb-11 22:40 
AnswerRe: New version of itextsharp Pin
la_morte5-Feb-11 7:12
memberla_morte5-Feb-11 7:12 
GeneralByte[] to File.pdf Pin
Member 362262327-Oct-10 13:12
memberMember 362262327-Oct-10 13:12 
GeneralRe: Byte[] to File.pdf Pin
Alaa-eddine KADDOURI27-Oct-10 22:22
memberAlaa-eddine KADDOURI27-Oct-10 22:22 
GeneralRe: Byte[] to File.pdf Pin
Member 362262327-Oct-10 22:32
memberMember 362262327-Oct-10 22:32 
GeneraliSafePDF v1.3.0 is out Pin
Alaa-eddine KADDOURI3-Sep-10 2:44
memberAlaa-eddine KADDOURI3-Sep-10 2:44 
GeneralSigning with store certificate Pin
ashishdhingra9-Aug-10 19:26
memberashishdhingra9-Aug-10 19:26 
GeneralRe: Signing with store certificate Pin
luisvilc2612-Aug-10 16:35
memberluisvilc2612-Aug-10 16:35 
Generalinvisible signature if cert is installed Pin
bbembi_de18-Jul-10 23:24
memberbbembi_de18-Jul-10 23:24 
GeneralNew article about digital signature Pin
Alaa-eddine KADDOURI2-Jun-10 9:23
memberAlaa-eddine KADDOURI2-Jun-10 9:23 
GeneralRe: New article about digital signature Pin
ashishdhingra23-Jun-10 20:15
memberashishdhingra23-Jun-10 20:15 
GeneralRe: New article about digital signature Pin
Alaa-eddine KADDOURI23-Jun-10 23:21
memberAlaa-eddine KADDOURI23-Jun-10 23:21 
GeneralNew version available Pin
Alaa-eddine KADDOURI23-Apr-10 2:51
memberAlaa-eddine KADDOURI23-Apr-10 2:51 
GeneralRe: New version available Pin
luisvilc2613-May-10 17:25
memberluisvilc2613-May-10 17:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150728.1 | Last Updated 17 Jun 2006
Article Copyright 2006 by Alaa-eddine KADDOURI
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid