Protect PDF document

You can protect a PDF document by setting the following parameters:

  • permissions
  • password to open document
  • password to change permissions

To protect a PDF document, follow these steps:

  1. Create an instance of the Viewer class. Specify the source document path as a constructor parameter.
  2. Instantiate the Security class.
  3. To specify a password to open the document, call the setDocumentOpenPassword() method.
  4. To specify a password to change restrictions, call the setPermissionsPassword() method.
  5. To specify the document permissions, call the setPermissions method.
  6. Instantiate the PdfViewOptions object. Specify the saving path format for the rendered document.
  7. Call the setSecurity method of the PdfViewOptions class. Specify object created in steps 2-5.
  8. Call the View.view() method of the Viewer object. Specify the PdfViewOptions object as the parameter.

The following code snippet shows how to protect the output PDF document:

import com.groupdocs.viewer.Viewer;
import com.groupdocs.viewer.options.PdfViewOptions;
import com.groupdocs.viewer.options.Permissions;
import com.groupdocs.viewer.options.Security;
// ...

try (Viewer viewer = new Viewer("sample.docx")) {
    // Specify the security settings.
    Security security = new Security();
    security.setDocumentOpenPassword("o123");
    security.setPermissionsPassword("p123");
    security.setPermissions(Permissions.ALLOW_ALL ^ Permissions.DENY_PRINTING);
    // Create a PDF file.
    PdfViewOptions viewOptions = new PdfViewOptions("output.pdf");
    // Apply the security settings.
    viewOptions.setSecurity(security);

    viewer.view(viewOptions);
}