I have created a small application in .net 8.0 to sign PDF documents with a certificate using a hardware token that requires a password via an authentication application. I am using FreeSpire.PDF 10.2.0. However, when I save the signed document file, the authentication application prompts me for the password twice and actually uses two timestamps (which are paid).
I have tried using the competing Syncfusion, where it works well.
I attach the code below:
- Code: Select all
private async Task<Stream> SignPdf(Stream file)
{
try
{
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, _options.CertificateThumbprint, false);
if (certCollection.Count == 0)
{
throw new Exception("Certificate not found!");
}
X509Certificate2 cert = certCollection[0];
// Load the PDF document
PdfDocument doc = new PdfDocument();
doc.LoadFromStream(file);
// Create a visible signature
PdfCertificate pdfCert = new PdfCertificate(cert);
PdfSignature pdfSignature = new PdfSignature(doc, doc.Pages[0], pdfCert, "signature");
pdfSignature.GraphicsMode = GraphicMode.SignImageOnly;
pdfSignature.SignImageLayout = SignImageLayout.Stretch;
string assemblyPath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
var signatureImagePath = Path.Combine(assemblyPath, "Content", "signature.png");
pdfSignature.SignImageSource = PdfImage.FromFile(signatureImagePath);
pdfSignature.ConfigureTimestamp(_options.TimeStampServer, _options.TimeStampUser, _options.TimeStampPassword);
var documentSize = doc.Pages[0].Size;
var currentSignatureWidth = _options.SignatureWidth;
var currentSignatureHeight = _options.SignatureHeight;
if (documentSize.Width < currentSignatureWidth)
{
currentSignatureWidth = documentSize.Width - _options.SignatureMargin;
}
if (documentSize.Height < currentSignatureHeight)
{
currentSignatureHeight = documentSize.Height - _options.SignatureMargin;
}
pdfSignature.Bounds = new RectangleF(new PointF(documentSize.Width - currentSignatureWidth - _options.SignatureMargin, documentSize.Height - currentSignatureHeight - _options.SignatureMargin), new SizeF(currentSignatureWidth, currentSignatureHeight));
// Save the signed PDF document
doc.SaveToStream(file);
return file;
}
catch (Exception ex)
{
throw new Exception("Error during signing of document.", ex);
}
}