I am working on one project using iTextSharp to digitally sign PDF file, it's workable, but need directly show the certificate's info on PDF (Please refer to attached image), how to do or set any parameter of iTextSharp?
public static X509Certificate2 cert;
//Sign with certificate selection in the windows certificate store
public static void Sign(string pdfFile, string outPdfFile){
Program.WriteLog("Signing Digital Certificate");
string IssuerName = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
IssuerName = Properties.Settings.Default.IssuerName;
if (IssuerName.Length > 0)
cert = store.Certificates.Find(X509FindType.FindByIssuerName, IssuerName, false)[0];
if (cert == null)
{
//manually chose the certificate in the store
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);
if (sel.Count > 0)
cert = sel[0];
else
{
Console.WriteLine("Certificate not found");
return;
}
}
PdfReader reader = new PdfReader(pdfFile); // source pdf file
FileStream os = new FileStream(outPdfFile, FileMode.Create); //the output pdf file
PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
stamper.SetEncryption(PdfWriter.STRENGTH128BITS, "", null, PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
try
{
Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };
IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
//here set signatureAppearance at your will
appearance.Reason = Properties.Settings.Default.DigitalSignReason;
appearance.Location = Properties.Settings.Default.DigitalSignLocation;
appearance.Contact = Properties.Settings.Default.DigitalSignContact;
if (Properties.Settings.Default.DigitalSignAppearance == 1)
{
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), 1, "Signed");
}
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
//MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES);
}catch(Exception e){
Console.WriteLine(e.Message, 1);
File.Delete(outPdfFile);
}
finally
{
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
}