您可以使用ExternalSignature
提供X509Certificate2
签名文档的对象。请使用以下代码片段。在这些示例中,Windows 证书存储用于获取用于签名的证书:
// The System.Security.dll assembly should be added into References
// Signing 1. Using SignatureField
public void Sign_With_SmartCard_1()
{
const string dataDir = @"c:\";
File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
{
using (Document doc = new Document(fs))
{
SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));
// Sign with certificate selection in the windows certificate store
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
// Manually chose the certificate in the store
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Forms.ExternalSignature(sel[0])
{
Authority = "Me",
Reason = "Reason",
ContactInfo = "Contact"
};
field1.PartialName = "sig1";
doc.Form.Add(field1, 1);
field1.Sign(externalSignature);
doc.Save();
}
}
using (PdfFileSignature pdfSign = new PdfFileSignature(dataDir + "externalSignature1.pdf"))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
}
// Signing 2. Using PdfFileSignature
public void Sign_With_SmartCard_2()
{
const string dataDir = @"c:\";
Document doc = new Document(dataDir + "blank.pdf");
using (PdfFileSignature pdfSign = new PdfFileSignature())
{
pdfSign.BindPdf(doc);
//Sign with certificate selection in the windows certificate store
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
//manually chose the certificate in the store
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Forms.ExternalSignature(sel[0]);
pdfSign.SignatureAppearance = dataDir + "demo.png";
pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
pdfSign.Save(dataDir + "externalSignature2.pdf");
}
using (PdfFileSignature pdfSign = new PdfFileSignature(dataDir + "externalSignature2.pdf"))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
}
我们希望这会有所帮助。如果您需要任何进一步的帮助,请随时与我们联系。