views:

606

answers:

1

Hello, I'm trying to digitally sign a PDF file using THIS project as an example.

When it executes st.Close(); I am getting the infamous "Object reference not set to instance of an object".

I have no idea of why this is happening, st is an instance of an object and it is used above. This exception is happening inside .Close() and as I do not have the source code i can only try to guess why...

All i can say is that:

  1. The original PDF is being successfully read.
  2. An empty pdf is being generated (I guess the .Close() will write the file).
  3. My certificate is being loaded, but I am not sure it's the right way to do it.

Here is How I'm loading the certificate:

private void processCert(X509Certificate2 card)
{
    X509CertificateParser cp = new org.bouncycastle.x509.X509CertificateParser(card.RawData);
    chain = new org.bouncycastle.x509.X509Certificate[] { cp.ReadCertificate() };
}

This is how I am trying to sign the PDF.

public string Sign(string SigReason, string SigContact, string SigLocation, bool visible)
{
    string bugLog ="";
    try
    {
        PdfReader reader = new PdfReader(this.inputPDF);

        //Activate MultiSignatures
        PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);

        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();
    }
    catch (Exception e)
    {
        bugLog += " ERROR Sign: " + e.Message;
    }

    return buglog;
  }

Has anyone got a though on why I am getting this exception, or what should i do to overcome this?

The iTextSharp Documentation has not been much help...

+1  A: 

I've now manage to make this work :) Some minor changes to this example did the trick ;)

http://itextpdf.sourceforge.net/howtosign.html#signextitextsharp2

Sergio