ImageGear .NET - Updated
Use PDF Security
User Guide > How to Work with... > PDF > How to... > Use PDF Security

A PDF document can be secured by encrypting its contents and requiring a password for access. Using ImageGear, apps can open and decrypt password-secured PDF documents provided that the correct password is supplied. Once a PDF document is opened, ImageGear enables apps to:

This sample illustrates the particulars of how to:

The following provides details of the sample and shows how to modify it to perform some of the other functions possible with ImageGear.

After initializing ImageGear, load the necessary ImageGear filters to create an instance of PDF format for output using code that looks like:

 
Copy Code
ImGearFileFormats.Filters.Add(ImGearPDF.CreatePDFFormat());

Next, the PDF library requires its own initialization:

 
Copy Code
ImGearPDF.Initialize();

Prior to opening any password-secured PDF documents, an authorization callback procedure must be registered using the ImGearPDFDocument.RegisterAuthProc() method:

 
Copy Code
ImGearPDFDocument.RegisterAuthProc(
   new ImGearPDFDocument.ImGearAuthProc(PDFAuthProc),
   ImGearPDFPermReqOpr.OPEN);

An app’s PDFAuthProc() callback is expected to provide the password using the ImGearPDFDocument.PermRequest() method.  An example callback would look like:

 
Copy Code
       private Boolean PDFAuthProc(ImGearPDFDocument pdfDocument, object ClientData)
       {
           ImGearPDFPermReqOpr targetOperation = (ImGearPDFPermReqOpr)ClientData;

           // Set or get from the user the password for the file.
           string password = "something";

           // Check the permissions associated with pdfDocument using the latest
           // permissions format and determine whether the targetOperation is
           // allowed for the specified object in the document.
           ImGearPDFPermReqStatus status = pdfDocument.PermRequest(ImGearPDFPermReqObj.DOC, targetOperation, password);

           // Return whether or not permission has been granted.    
           return (status == ImGearPDFPermReqStatus.GRANTED);
       }

When the ImGearFileFormats.LoadDocument() method attempts to open a secure PDF that requires a password, the registered callback is invoked.The callback provides the password and authenticates it. If the PDF document does not require a Document Open Password, then the callback is not called and the file is immediately opened. In both cases, use the LoadDocument method to open all pages of the document as follows:

 
Copy Code
ImGearDocument igDocument;
using (FileStream fileStream = new FileStream(inputFileName, FileMode.Open,
       FileAccess.Read, FileShare.Read))
{
   igDocument = ImGearFileFormats.LoadDocument(fileStream);
}

After the document has been successfully opened, its security settings, i.e., encryption and password, can be managed. First, it is necessary to request permission to change the security settings by using the ImGearPDFDocument.PermRequest() method and then checking whether that permission  has been granted:

 
Copy Code
         ImGearPDFDocument pdfOutput = igDocument as ImGearPDFDocument;
         ImGearPDFPermReqStatus status = pdfOutput.PermRequest(
           ImGearPDFPermReqObj.DOC, ImGearPDFPermReqOpr.SECURE, "");
         if (status == ImGearPDFPermReqStatus.GRANTED)
                   // make the changes here

After access has been granted, secure a PDF document with a new password and 256-bit AES encryption by creating a new ImGearPDFSecurityData object and setting its fields as follows:

 
Copy Code
        ImGearPDFSecurityData securityData = new ImGearPDFSecurityData();
         // Add all permissions, including OPEN and SECURE.
         // Use other flags to select individual permissions, if desired.
         securityData.Perms = ImGearPDFPermsFlags.ALL;
         // Add support for Acrobat 9.0 and up.
         securityData.Revision = ImGearPDFRevision.REVISION_5;
         // Set encryption key length in bytes.
         securityData.KeyLength = 32;
         // Use 256-bit AES algorithm for encryption.
         securityData.EncryptMethod = ImGearPDFStdSecurityMethod.AES_V2;
         // Set these values to encrypt metadata and attachments, if desired.
         securityData.EncryptMetadata = true;
         securityData.EncryptAttachmentsOnly = false;
         // Set the password.
         securityData.NewUserPW = true;
         securityData.UserPW = password;

Then set the CryptHandler and SecurityData for the document as follows:

 
Copy Code
         // Set up the encryption handler and the new security data.
         ImGearPDFAtom cryptHandler = new ImGearPDFAtom("Standard");
         pdfDoc.SetNewCryptHandler(cryptHandler);
         pdfDoc.SetNewSecurityData(securityData);

If the document is already a secured document, it is possible to create all new security features using the code described above and in the sample. It is also possible to change only specific security settings and leave others unchanged. For example, to change only the password of an already-encrypted PDF document, create an ImGearPDFSecurityData object into which is retrieved the existing security data for the document instead of creating a new, empty ImGearPDFSecurityData object, and then change only the password fields, leaving the other fields unchanged. Code to do this could look like:

 
Copy Code
         // Retrieve the existing security data.
         ImGearPDFSecurityData securityData = pdfDoc.GetSecurityData();
                          if (securityData != null)
                          {
            // Change the password.
            securityData.NewUserPW = true;
            securityData.UserPW = password;
            // Set up to use the modified security data.
            pdfDoc.SetNewSecurityData(securityData);
                          }

As another option, use the ImGearPDFDocument.SetNewCryptHandler() method with a null argument to remove all security from a secure PDF document. In this case there is no need to use the ImGearPDFDocument.SetNewSecurityData() method. Processing after opening the document is simply:

 
Copy Code
         pdfOutput.SetNewCryptHandler(null);

Finally, after the security settings are newly set or updated, or the security is removed completely, use the ImGearPDFDocument.Save() method with the saving format set to ImGearSavingFormats.PDF to write the PDF document:

 
Copy Code
using (FileStream fileStream = new FileStream(outputFileName, FileMode.Create,
       FileAccess.ReadWrite))
{
   pdfOutput.Save(fileStream, ImGearSavingFormats.PDF, 0, 0, (int)ImGearPDFPageRange.ALL_PAGES, ImGearSavingModes.OVERWRITE);
}