Documents for PDF, .NET Edition Documentation
Features / Security
In This Topic
    Security
    In This Topic

    PDF security can be maintained by controlling access to PDF documents by encrypting PDF, setting permission levels and adding or removing digital signature that will prevent unauthorized users from stealing information in your PDF document. For more information on PDF security, see PDF specification 1.7 (Section 7.6.3).

    The GcPdf library supports some of the standard security options in the PDF file format. The following section describes the different types of security features.

    Encrypt PDF

    PDF documents with sensitive or confidential information require encryption to restrict access to intruders. GcPdf provides Security class to encrypt a document and decline access to unauthorized users.

    To encrypt a PDF file:

    1. Create an object of StandardSecurityHandlerRev4 class.
    2. Set the required properties of the StandardSecurityHandlerRev4 object, such as passwords, encryption algorithm, etc.
    3. Pass the object to the EncryptHandler property of the Security class to encrypt the PDF document.
      C#
      Copy Code
      public void CreatePDF(Stream stream)
      {
          GcPdfDocument doc = new GcPdfDocument();
          var page = doc.NewPage();
          var g = page.Graphics;
          const float In = 150;
          //Add Encryption
          var std = new StandardSecurityHandlerRev4();
          std.OwnerPassword = "abc";
          std.UserPassword = "qwe";
          // Set EncyptionAlgorithm
          std.EncryptionAlgorithm = EncryptionAlgorithm.RC4;
          std.EncryptionKeyLength = 128;
          // Set the EncryptHandler property.
          doc.Security.EncryptHandler = std;
          // Render text using DrawString method
          g.DrawString("Welcome to GrapeCity, Inc", new TextFormat()
          { Font = StandardFonts.TimesBold, FontSize = 12 }, new PointF(In, In));
          // Save document
          doc.Save(stream);
      }
      
    Back to Top

    Set Permissions

    Setting permissions restricts users from copying, printing and editing the contents in a PDF document. The Security class of the GcPdf library allows a user to set up permissions in a PDF document.

    To set permissions in a PDF document:

    1. Create an object of StandardSecurityHandlerRev3 class.
    2. Use the required properties of the StandardSecurityHandlerRev3 object to set the permissions such as editing, printing, etc.
    3. Pass the object to the EncryptHandler property of the Security class.
      C#
      Copy Code
      public void CreatePDF(Stream stream)
      {
          GcPdfDocument doc = new GcPdfDocument();
          var page = doc.NewPage();
          var g = page.Graphics;
          int In = 72;
      
          // Create a security handler variable
          var std = new StandardSecurityHandlerRev3();
          std.EditingPermissions = EditingPermissions.Enabled;
          std.OwnerPassword = "abc";
          std.UserPassword = "qwe";
      
          // Set permissions
          std.EditingPermissions = EditingPermissions.Enabled;
          std.CopyContentPermissions = CopyContentPermissions.Enabled;
          std.PrintingPermissions = PrintingPermissions.Disabled;
          doc.Security.EncryptHandler = std;
      
          // Render text using DrawString method
          g.DrawString("Welcome to GrapeCity, Inc.", new TextFormat()
          { Font = StandardFonts.TimesBold, FontSize = 12 }, new PointF(In, In));
      
          // Save document
          doc.Save(stream);
      }
      
    Back to Top

    Digital Signature

    GcPdf enables a user to digitally sign a PDF document to secure the authenticity of the content. The library supports digital signature in the PDF document using the SignatureField class. You can also add digital signatures with timestamps to mark the time and date of the signature in the PDF document. GcPdf supports legal stamps created by trustworthy authority like the Time Stamp Authority (TSA).

    Further, GcPdf allows a user to reuse a signed PDF template by removing the signatures and keeping the Signature Field, or simply removing the Signature Field.

    Add Digital Signature

    To add digital signature in a PDF document:

    1. Use the SignatureProperties class to set up the certificate for digital signature.
    2. Initialize the SignatureField class to hold the signature.
    3. Add the signature field to the PDF document using the Add method.
    4. Connect the signature field to signature properties.
    5. Sign the document using the Sign method of GcPdfDocument class. It also saves the document.
      C#
      Copy Code
      public static void CreatePDF(Stream stream)
      {
          GcPdfDocument doc = new GcPdfDocument();
          Page page = doc.NewPage();
          TextFormat tf = new TextFormat() { Font = StandardFonts.Times, FontSize = 14 };
          page.Graphics.DrawString(
              "Hello, World!\r\nSigned below by GcPdfWeb SignDoc sample." +
              "\r\n(Note that some browser built-in viewers may not show the signature.)",
              tf, new PointF(72, 72));
      
          // Initialize a test certificate:
          var pfxPath = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
          X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
          X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
          | X509KeyStorageFlags.Exportable);
          SignatureProperties sp = new SignatureProperties();
          sp.Certificate = cert;
          sp.Location = "GcPdfWeb Sample Browser";
          sp.SignerName = "GcPdfWeb";
          // Add timestamp            
          sp.TimeStamp = new TimeStamp("https://freetsa.org/tsr");
      
          // Initialize a signature field to hold the signature:
          SignatureField sf = new SignatureField();
          sf.Widget.Rect = new RectangleF(72, 72 * 2, 72 * 4, 36);
          sf.Widget.Page = page;
          sf.Widget.BackColor = Color.LightSeaGreen;
          sf.Widget.TextFormat.Font = StandardFonts.Helvetica;
          sf.Widget.ButtonAppearance.Caption = $"Signer: " +
              $"{sp.SignerName}\r\nLocation: {sp.Location}";
          // Add the signature field to the document:
          doc.AcroForm.Fields.Add(sf);
      
          // Connect the signature field and signature properties:
          sp.SignatureField = sf;
      
          // Sign and save the document:
          // NOTES:
          // - Signing and saving is an atomic operation, the two cannot be separated.
          // - The stream passed to the Sign() method must be readable.
          doc.Sign(sp, stream);
      
          // Rewind the stream to read the document just created 
          // into another GcPdfDocument and verify the signature:
          stream.Seek(0, SeekOrigin.Begin);
          GcPdfDocument doc2 = new GcPdfDocument();
          doc2.Load(stream);
          SignatureField sf2 = (SignatureField)doc2.AcroForm.Fields[0];
          if (!sf2.Value.VerifySignature())
              throw new Exception("Failed to verify the signature");
      
          // Done (the generated and signed document has already been saved to 'stream').
      }
      

    Back to Top

    Remove Digital Signature

    With GcPdf, it is easy to remove a digital signature from a PDF file. The library allows users to remove a signature from signature field, so that the contents of the PDF file can be used again.

    To remove the signature and keep the signature field in the PDF document, follow these steps:

    1. Initialize an instance of GcPdfDocument class and load the PDF file.
    2. To remove all the signatures in the document, call a recursive method which loops through all the signature fields in the PDF file and set the Value property of the SignatureField class to null.
    3. Save the document.
      C#
      Copy Code
      var doc = new GcPdfDocument();
      using (var fs = new FileStream( "TimeSheet.pdf", FileMode.Open, FileAccess.Read))
      {
          doc.Load(fs);
      
          // Fields can be children of other fields, so we use
          // a recursive method to iterate through the whole tree:
          removeSignatures(doc.AcroForm.Fields);
      
          doc.Save("TimeSheet_NoSign.pdf"); //Save the document
      
          void removeSignatures(FieldCollection fields)
          {
              foreach (var f in fields)
              {
                  if (f is SignatureField sf)
                      sf.Value = null; //removes the signatures from the document
                  removeSignatures(f.Children);
              }
          }
      }
      

     

    Back to Top

    Extract Signature Properties

    GcPdf allows you to extract signature information from a digital signature in a PDF document by using Content property of Signature class. The signature information provides necessary details about the signature which can be used to verify its validity. Some of the information fields which can be extracted from a signature are Issuer, IssuerName, SerialNumber, Subject, Thumbprint, NotAfter, NotBefore, SignatureAlgorithm etc.

    To extract signature information from a digital signature in PDF document, follow these steps:

    1. Load the signed document and get the signature using Fields property of AcroForm class.
    2. Use the Content property of Signature class to get the additional information about the signature.
      C#
      Copy Code
      MemoryStream ms = new MemoryStream(File.ReadAllBytes(@"AdobePDFWithEmptySignatureField.pdf"));
      GcPdfDocument doc = new GcPdfDocument();
      doc.Load(ms);
      
      //initialize a certificate
      X509Certificate2 cert = new X509Certificate2(@"User.pfx", "User12");
      SignatureProperties sp = new SignatureProperties();
      sp.SignatureFormat = SignatureFormat.PKCS7Detached;
      sp.SignatureDigestAlgorithm = SignatureDigestAlgorithm.SHA1;
      sp.Certificate = cert;
      sp.Location = "MACHINE";
      sp.SignerName = "USER";
      sp.SigningDateTime = null;
      sp.SignatureField = doc.AcroForm.Fields["EmptySignatureField"];
       
      using (MemoryStream ms2 = new MemoryStream())
      {
          //sign document
          doc.Sign(sp, ms2, false);
          ms2.Seek(0, SeekOrigin.Begin);
       
          //load signed document
          GcPdfDocument doc2 = new GcPdfDocument();
          doc2.Load(ms2);
       
          //get signature field and signature
          SignatureField sf2 = (SignatureField)doc2.AcroForm.Fields["EmptySignatureField"];
          var sk = sf2.Value.Content;
      
          //get certificate and print its props
          var sc = sk.SigningCertificate;
          Console.WriteLine($"Subject: {sc.Subject}");
          Console.WriteLine($"Issuer: {sc.Issuer}");
          Console.WriteLine($"GetEffectiveDateString: {sc.GetEffectiveDateString()}");
          Console.WriteLine($"GetExpirationDateString: {sc.GetExpirationDateString()}");
      }
      
    Back to Top

    For more information on applying security using GcPdf, see GcPdf sample browser.