iTextSharp - Signing a PDF

D

Doug

Submitted by SoDakDoogie on Mon, 01/07/2013 - 14:59

I am building code that will allow me to add a signature image (i.e. "Appearance") and a digital id to a signature field. The code works fine - if thesignature field is large. If the signature field is not very big, the image (appearance) won't show up. However, when I add the image manually it does. I have looked for days and cannot figure out why this is the case. Belowis an example of the code I'm using. Any idea why this doesn't work?

using iTextSharp.text;
using iTextSharp.text.pdf;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;

public bool Sign(string signatureField, string digitalId, string digitalPassword, string signatureImage)
{
bool signed = false;

try
{
string alias = null;
FileStream digitalFile = new FileStream(digitalId, FileMode.Open, FileAccess.Read);

Pkcs12Store store = new Pkcs12Store(digitalFile, digitalPassword.ToCharArray());

IEnumerator enumerator = store.Aliases.GetEnumerator();

while (enumerator.MoveNext())
{
alias = ((string)enumerator.Current);

if (store.IsKeyEntry(alias))
{
break;
}
}

AsymmetricKeyParameter key = store.GetKey(alias).Key;
X509CertificateEntry[] certificateEntry = store.GetCertificateChain(alias);
X509Certificate[] chain = new X509Certificate[certificateEntry.Length];

for (int index = 0; index < certificateEntry.Length; index++)
{
chain[index] = certificateEntry[index].Certificate;
}

PdfSignatureAppearance appearance = _stamper.SignatureAppearance;

iTextSharp.text.Image sigImage = iTextSharp.text.Image.GetInstance(signatureImage);
appearance.SignatureGraphic = sigImage;
appearance.Render = PdfSignatureAppearance.SignatureRender.GraphicAndDescription;

appearance.SetVisibleSignature(signatureField);
appearance.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

signed = true;
}
catch(Exception ex)
{
signed = false;
throw ex;
}

return signed;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top