This example demonstrates how to programmatically add a signature field to a PDF document and digitally sign it using a certificate. The process involves creating or loading a PDF, inserting a signature field via Aspose.PDF’s FormEditor, and then applying a PKCS7 digital signature using PdfFileSignature. This is useful for automating secure document workflows such as contract signing, compliance verification, or internal approvals.
Steps to Add a Signature Field and Digitally Sign a PDF using C#
- Ensure a source PDF exists — If no
source.pdfis present, create a minimal one-page document. - Generate a self-signed certificate — If
certificate.pfxis missing, create a 2048-bit RSA key pair and self-sign an X.509 certificate valid for one year. - Add a signature field — Load the PDF, use FormEditor.AddField() to insert a signature field named “Signature1” on page 1 at coordinates (100,100) to (250,150).
- Save the PDF with the field — Persist the updated document as
temp_with_field.pdf. - Configure and apply the digital signature — Bind the temporary PDF to PdfFileSignature, load the certificate, and set signature metadata (reason, contact, location).
- Sign the document — Call Sign() using the field name “Signature1” and save the result as
signed_output.pdf.
Code to Add a Signature Field and Digitally Sign a PDF using C#
The example illustrates the full end-to-end process of preparing a PDF for signing, inserting a signature field, and applying a cryptographically secure digital signature using a self-signed certificate — all without user interaction.