Add a digital signature to a PDF in C#
Nutrient .NET SDK (formerly GdPicture.NET) enables you to do the following:
- Add a certified digital signature to a PDF.
- Get a digital signature’s properties.
- Remove a certified digital signature.
- Add a certified digital signature from other sources.
Adding a certified digital signature to a PDF
To add a certified digital signature, follow these steps:
- Create a digital ID or use an already created one.
- Set the certificate contained in the digital ID stored in the
PCKS#12file or aStreamobject with theSetSignatureCertificateFromP12method. - Recommended: Specify the signature information with the
SetSignatureInfomethod. It requires the following string parameters:Name— The person or authority signing the document.Reason— The reason for signing.Location— The physical location where the signing takes place.ContactInfo— The contact information of the signer.
- Optional: Set the signature’s location on the currently selected page. If you skip this step, the signature will be invisible.
- Set the measurement unit with the
SetMeasurementUnitmethod. - Select the page where the signature is placed with the
SelectPagemethod. - Set the signature position and dimensions with the
SetSignaturePosmethod.
- Set the measurement unit with the
- Optional: Configure the text with the
SetSignatureTextmethod. For more information on how to use this method, go to the Signing a Digital Signature with Text section. - Optional: Add an image inside the bounding box of the signature. For more information on how to use this method, go to the Signing a Digital Signature with an Image section.
- Apply the signature with the
ApplySignaturemethod using the specified settings, and save the PDF document to a file or aStreamobject. It requires the following parameters:OutputFileNameorOutputStream— Either the path to the output file or aStreamobject.SignatureMode— A member of thePdfSignatureModeenumeration that specifies the electronic signature technology used in the signing process.Linearization— Specifies if the output PDF document is linearized.
You can only add digital signatures to non-encrypted documents.
To add a digital signature using text and an image to the last page of a PDF document, use the following code:
using GdPicturePDF gdPicturePDF = new GdPicturePDF();gdPicturePDF.LoadFromFile(@"C:\temp\source.pdf");// Set the certificate from a file.gdPicturePDF.SetSignatureCertificateFromP12(@"C:\temp\certificate.pfx", "nutrient");// Add additional signature information.gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io");// Set the measurement unit to centimeters.gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter);float width = gdPicturePDF.GetPageWidth();// Select the last page.gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount());// Define the signature boundary box position and dimensions.gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2);// Select the text font type.string fontName = gdPicturePDF.AddTrueTypeFont("Freestyle Script", false, false, false);// Save the text alignment to center in a variable.var center = TextAlignment.TextAlignmentCenter;// Draw the text to the signature boundary box.gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, true);// Add an image resource from a file.string stampImage = gdPicturePDF.AddJpegImageFromFile(@"C:\temp\source.jpg");// Draw the image resource to the signature boundary box.gdPicturePDF.SetSignatureStampImage(stampImage);// Save the output to a file.gdPicturePDF.ApplySignature(@"C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, false);Using gdPicturePDF As GdPicturePDF = New GdPicturePDF() gdPicturePDF.LoadFromFile("C:\temp\source.pdf") ' Set the certificate from a file. gdPicturePDF.SetSignatureCertificateFromP12("C:\temp\certificate.pfx", "nutrient") ' Add additional signature information. gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io") ' Set the measurement unit to centimeters. gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter) Dim width As Single = gdPicturePDF.GetPageWidth() ' Select the last page. gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount()) ' Define the signature boundary box position and dimensions. gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2) ' Select the text font type. Dim fontName As String = gdPicturePDF.AddTrueTypeFont("Freestyle Script", False, False, False) ' Save the text alignment to center in a variable. Dim center = TextAlignment.TextAlignmentCenter ' Draw the text to the signature boundary box. gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, True) ' Add an image resource from a file. Dim stampImage As String = gdPicturePDF.AddJpegImageFromFile("C:\temp\source.jpg") ' Draw the image resource to the signature boundary box. gdPicturePDF.SetSignatureStampImage(stampImage) ' Save the output to a file. gdPicturePDF.ApplySignature("C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, False)End UsingSigning a digital signature with text
To sign a PDF document with a digital signature using text, follow these steps:
- Create a digital ID or use an already created one.
- Set the certificate contained in the digital ID stored in the
PCKS#12file or aStreamobject with theSetSignatureCertificateFromP12method. - Recommended: Specify the signature information with the
SetSignatureInfomethod. It requires the following string parameters:Name— The person or authority signing the document.Reason— The reason for signing.Location— The physical location where the signing takes place.ContactInfo— The contact information of the signer.
- Set the signature’s location on the currently selected page. If you skip this step, the signature will be invisible.
- Set the measurement unit with the
SetMeasurementUnitmethod. - Select the page where the signature is placed with the
SelectPagemethod. - Set the signature position and dimensions with the
SetSignaturePosmethod.
- Set the measurement unit with the
- Configure the text with the
SetSignatureTextmethod. It uses the following parameters:Text— The text to be displayed. If this parameter is an empty string, the text displays the data from theSetSignatureInfomethod.FontResName— The font name used. Use either theAddTrueTypeFontmethod or theAddStandardFontmethod. If this parameter is an empty string, the predefined font is used.FontSize— The text font size in points.- Font color — The font color can be set with one of the following ways: a
Colorobject, a set of four byte parameters (Cyan,Magenta,Yellow,Black), or a 32-bit signed integer. AlignHorz— The horizontal text alignment within the bounding box. Use theTextAlignmentenumeration.AlignVert— The vertical text alignment within the bounding box. Use theTextAlignmentenumeration.TextDecorationStyle— Optional: A member of thePdfTextDecorationStyleenumeration. It specifies if the text has an overline, strikethrough, or underline.ShowText— A Boolean value that specifies whether the text is displayed.
- Apply the signature with the
ApplySignaturemethod using the specified settings, and save the PDF document to a file or aStreamobject. It requires the following parameters:OutputFileNameorOutputStream— Either the path of the output file or aStreamobject.SignatureMode— A member of thePdfSignatureModeenumeration that specifies the electronic signature technology used in the signing process.Linearization— Specifies if the output PDF document is linearized.
To add a digital signature using text to the last page of a PDF document, use the following code:
using GdPicturePDF gdPicturePDF = new GdPicturePDF();gdPicturePDF.LoadFromFile(@"C:\temp\source.pdf");// Set the certificate from a file.gdPicturePDF.SetSignatureCertificateFromP12(@"C:\temp\certificate.pfx", "nutrient");// Add additional signature information.gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io");// Set the measurement unit to centimeters.gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter);float width = gdPicturePDF.GetPageWidth();// Select the last page.gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount());// Define the signature boundary box position and dimensions.gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2);// Select the text font type.string fontName = gdPicturePDF.AddTrueTypeFont("Freestyle Script", false, false, false);// Save the text alignment to center in a variable.var center = TextAlignment.TextAlignmentCenter;// Draw the text to the signature boundary box.gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, true);// Save the output to a file.gdPicturePDF.ApplySignature(@"C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, false);Using gdPicturePDF As GdPicturePDF = New GdPicturePDF() gdPicturePDF.LoadFromFile("C:\temp\source.pdf") ' Set the certificate from a file. gdPicturePDF.SetSignatureCertificateFromP12("C:\temp\certificate.pfx", "nutrient") ' Add additional signature information. gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io") ' Set the measurement unit to centimeters. gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter) Dim width As Single = gdPicturePDF.GetPageWidth() ' Select the last page. gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount()) ' Define the signature boundary box position and dimensions. gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2) ' Select the text font type. Dim fontName As String = gdPicturePDF.AddTrueTypeFont("Freestyle Script", False, False, False) ' Save the text alignment to center in a variable. Dim center = TextAlignment.TextAlignmentCenter ' Draw the text to the signature boundary box. gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, True) gdPicturePDF.ApplySignature("C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, False)End UsingSigning a digital signature with an image
To sign a PDF document with a digital signature using an image — for example, one containing a scan of a handwritten signature — follow these steps:
- Create a digital ID or use an already created one.
- Set the certificate contained in the digital ID stored in the
PCKS#12file or aStreamobject with theSetSignatureCertificateFromP12method. - Recommended: Specify the signature information with the
SetSignatureInfomethod. It requires the following string parameters:Name— The person or authority signing the document.Reason— The reason for signing.Location— The physical location where the signing takes place.ContactInfo— The contact information of the signer.
- Set the signature’s location on the currently selected page. If you skip this step, the signature will be invisible.
- Set the measurement unit with the
SetMeasurementUnitmethod. - Select the page where the signature is placed with the
SelectPagemethod. - Set the signature position and dimensions with the
SetSignaturePosmethod.
- Set the measurement unit with the
- Add an image inside the bounding box of the signature. If the
SetSignatureTextmethod is also used, the image is placed at the right side of the bounding box:- Add the image resource directly from a JPEG image with the
AddJpegImageFromFilemethod. - Use the
SetSignatureStampImagemethod to place the image resource inside the signature bounding box.
- Add the image resource directly from a JPEG image with the
- Apply the signature with the
ApplySignaturemethod using the specified settings, and save the PDF document to a file or aStreamobject. It requires the following parameters:OutputFileNameorOutputStream— Either the path of the output file or aStreamobject.SignatureMode— A member of thePdfSignatureModeenumeration that specifies the electronic signature technology used in the signing process.Linearization— Specifies if the output PDF document is linearized.
If the SetSignatureText method is also used, the image is placed at the right side of the bounding box.
To add a digital signature with an image to the last page of a PDF document, use the following code:
using GdPicturePDF gdPicturePDF = new GdPicturePDF();gdPicturePDF.LoadFromFile(@"C:\temp\source.pdf");// Set the certificate from a file.gdPicturePDF.SetSignatureCertificateFromP12(@"C:\temp\certificate.pfx", "nutrient");// Add additional signature information.gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io");// Set the measurement unit to centimeters.gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter);float width = gdPicturePDF.GetPageWidth();// Select the last page.gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount());// Define the signature boundary box position and dimensions.gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2);// Select the text font type.string fontName = gdPicturePDF.AddTrueTypeFont("Freestyle Script", false, false, false);// Save the text alignment to center in a variable.var center = TextAlignment.TextAlignmentCenter;// Draw the text to the signature boundary box.gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, true);// Add an image resource from a file.string stampImage = gdPicturePDF.AddJpegImageFromFile(@"C:\temp\source.jpg");// Draw the image resource to the signature boundary box.gdPicturePDF.SetSignatureStampImage(stampImage);// Save the output to a file.gdPicturePDF.ApplySignature(@"C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, false);Using gdPicturePDF As GdPicturePDF = New GdPicturePDF() gdPicturePDF.LoadFromFile("C:\temp\source.pdf") ' Set the certificate from a file. gdPicturePDF.SetSignatureCertificateFromP12("C:\temp\certificate.pfx", "nutrient") ' Add additional signature information. gdPicturePDF.SetSignatureInfo("John Smith", "Confidential", "Vienna (Austria)", "john.smith@nutrient.io") ' Set the measurement unit to centimeters. gdPicturePDF.SetMeasurementUnit(PdfMeasurementUnit.PdfMeasurementUnitCentimeter) Dim width As Single = gdPicturePDF.GetPageWidth() ' Select the last page. gdPicturePDF.SelectPage(gdPicturePDF.GetPageCount()) ' Define the signature boundary box position and dimensions. gdPicturePDF.SetSignaturePos(width - 7, 10, 5, 2) ' Select the text font type. Dim fontName As String = gdPicturePDF.AddTrueTypeFont("Freestyle Script", False, False, False) ' Save the text alignment to center in a variable. Dim center = TextAlignment.TextAlignmentCenter ' Draw the text to the signature boundary box. gdPicturePDF.SetSignatureText("John Smith", fontName, 12, GdPictureColor.Blue, center, center, True) ' Add an image resource from a file. Dim stampImage As String = gdPicturePDF.AddJpegImageFromFile("C:\temp\source.jpg") ' Draw the image resource to the signature boundary box. gdPicturePDF.SetSignatureStampImage(stampImage) ' Save the output to a file. gdPicturePDF.ApplySignature("C:\temp\output.pdf", PdfSignatureMode.PdfSignatureModeAdobePPKMS, False)End UsingAdditional digital signing settings
The list below contains methods that provide additional settings when using a certified digital signature. Use them after the SetSignatureCertificateFromP12 method and before the ApplySignature method:
- The
SetSignatureValidationMarkmethod adds the validation icon inside the signature with theSetSignatureValidationMarkmethod. - The
SetSignatureCertificationLevelmethod specifies the signature’s certification level. It uses thePdfSignatureCertificationLevelenumeration as its parameter. This parameter enables you to define the access permissions granted by the signature. - The
SetSignatureHashmethod sets the hash algorithm used in the signing. It uses thePdfSignatureHashenumeration as its parameter. - The
SetSignatureTimestampInfomethod sets the timestamp information.
Getting digital signature properties
To get the properties of a certified digital signature inside a PDF document, follow these steps:
- Use the
GetSignatureCountmethod to get the total number of signatures. - Loop through all signatures and use the
GetSignaturePropertiesmethod. It requires the signature index and the following list of output reference parameters:SignatureName— The name of the person or authority signing the document.SignatureReason— The reason for signing the document.SignatureLocation— The physical location where the signing took place.SignatureContactInfo— The contact information of the signer.SignatureDate— The time of signing as a string.StampLeft— The horizontal coordinate of the signature’s closest point to the currently defined origin. The returned value is expressed in the units specified by theSetMeasurementUnitmethod.StampTop— The vertical coordinate of the signature’s closest point to the currently defined origin. The returned value is expressed in the units specified by theSetMeasurementUnitmethod.StampWidth— The width of the signature’s bounding box, expressed in the current units defined by theSetMeasurementUnitmethod.StampHeight— The height of the signature’s bounding box, expressed in the current units defined by theSetMeasurementUnitmethod.StampPage— The page number where the signature is.DocumentValid— A Boolean value that specifies whether the document has been altered or corrupted since it was signed.CertificateValid— A Boolean value that specifies whether the certificate used is verified.CertificateFriendlyName— The name of the certificate’s owner.CertificateIssuer— The name of the authority that issued the certificate.CertificateNotBefore— The earliest time and date when the used certificate was valid.CertificateNotAfter— The time and date after which the used certificate is no longer valid.CertificateSubject— The entity the used certificate belongs to (a person or an organization).CertificateVersion— The version of the used certificate.SigningTime— The date and time when the document was signed. Only use this value when the time of signing isn’t available in the signature.SignatureLevel— A member of thePdfSignatureCertificationLevelenumeration that represents the level of the signature certification.
If you have only one signature in a PDF document, you can skip the GetSignatureCount method and use the GetSignatureProperties method with the signature index set to 0 as its parameter.
To list the properties of all certified digital signatures in a PDF document, use the following code:
using GdPicturePDF gdPicturePDF = new GdPicturePDF();gdPicturePDF.LoadFromFile(@"C:\temp\source.pdf");// Initiate all reference parameters.string SignatureName = "", SignatureReason = "", SignatureLocation = "", SignatureContactInfo = "";string SignatureDate = "", CertificateFriendlyName = "", CertificateIssuer = "", CertificateSubject = "";float StampLeft = 0, StampTop = 0, StampWidth = 0, StampHeight = 0;int StampPage = 0, CertificateVersion = 0;bool DocumentValid = false, CertificateValid = false;DateTime CertificateNotBefore = new DateTime();DateTime CertificateNotAfter = new DateTime();DateTime SigningTime = new DateTime();PdfSignatureCertificationLevel SignatureLevel = PdfSignatureCertificationLevel.NotCertified;
// Get the total amount of signatures.int signatureCount = gdPicturePDF.GetSignatureCount();for (int i = 0; i <= signatureCount - 1; i++){ // Get the properties of a signature. gdPicturePDF.GetSignatureProperties(i, ref SignatureName, ref SignatureReason, ref SignatureLocation, ref SignatureContactInfo, ref SignatureDate, ref StampLeft, ref StampTop, ref StampWidth, ref StampHeight, ref StampPage, ref DocumentValid, ref CertificateValid, ref CertificateFriendlyName, ref CertificateIssuer, ref CertificateNotBefore, ref CertificateNotAfter, ref CertificateSubject, ref CertificateVersion, ref SigningTime, ref SignatureLevel); // Write the signature name, reason, and signing date to the console. Console.WriteLine("Signature nr {0}:\n- Name: {1}\n- Reason: {2}\n- Date Signed: {3}", i, SignatureName, SignatureReason, SignatureDate);}Using gdPicturePDF As GdPicturePDF = New GdPicturePDF() gdPicturePDF.LoadFromFile("C:\temp\source.pdf") ' Initiate all reference parameters. Dim SignatureName = "", SignatureReason = "", SignatureLocation = "", SignatureContactInfo = "" Dim SignatureDate = "", CertificateFriendlyName = "", CertificateIssuer = "", CertificateSubject = "" Dim StampLeft As Single = 0, StampTop As Single = 0, StampWidth As Single = 0, StampHeight As Single = 0 Dim StampPage = 0, CertificateVersion = 0 Dim DocumentValid = False, CertificateValid = False Dim CertificateNotBefore As Date = New DateTime() Dim CertificateNotAfter As Date = New DateTime() Dim SigningTime As Date = New DateTime() Dim SignatureLevel As PdfSignatureCertificationLevel = PdfSignatureCertificationLevel.NotCertified
' Get the total amount of signatures. Dim signatureCount As Integer = gdPicturePDF.GetSignatureCount() For i = 0 To signatureCount - 1 ' Get the properties of a signature. gdPicturePDF.GetSignatureProperties(i, SignatureName, SignatureReason, SignatureLocation, SignatureContactInfo, SignatureDate, StampLeft, StampTop, StampWidth, StampHeight, StampPage, DocumentValid, CertificateValid, CertificateFriendlyName, CertificateIssuer, CertificateNotBefore, CertificateNotAfter, CertificateSubject, CertificateVersion, SigningTime, SignatureLevel) ' Write the signature name, reason, and signing date to the console. Console.WriteLine("Signature nr {0}:" & vbLf & "- Name: {1}" & vbLf & "- Reason: {2}" & vbLf & "- Date Signed: {3}", i, SignatureName, SignatureReason, SignatureDate) NextEnd UsingRemoving a certified digital signature
To remove a certified digital signature, use the RemoveSignature method. It requires only the signature index as its parameter. Use the GetSignatureCount method to get the total number of signatures.
If you have only one signature in a PDF document, you can skip the GetSignatureCount method and use the RemoveSignature method with the signature index set to 0 as its parameter.
To delete all certified digital signatures, use the following code:
using GdPicturePDF gdPicturePDF = new GdPicturePDF();gdPicturePDF.LoadFromFile(@"C:\temp\source.pdf");// Get the total amount of signatures.int signatureCount = gdPicturePDF.GetSignatureCount();for (int i = 0; i <= signatureCount - 1; i++){ // Remove the signature. gdPicturePDF.RemoveSignature(0);}gdPicturePDF.SaveToFile(@"C:\temp\output.pdf");Using gdPicturePDF As GdPicturePDF = New GdPicturePDF() gdPicturePDF.LoadFromFile("C:\temp\source.pdf") ' Get the total amount of signatures. Dim signatureCount As Integer = gdPicturePDF.GetSignatureCount() For i = 0 To signatureCount - 1 ' Remove the signature. gdPicturePDF.RemoveSignature(0) Next
gdPicturePDF.SaveToFile("C:\temp\output.pdf")End UsingAdding a certified digital signature from other sources
To add a certified digital signature from sources other than a PFX file, such as a smart card or a Windows certificate store, use the following methods:
SetSignatureCertificateFromSmartCardSetSignatureCertificateFromSmartCardBySerialNumberSetSignatureCertificateFromStore