Skip to content

PDFDocument: How To Encrypt PDFs

One of the PDFDocument features added in Xojo 2022r2 is the ability to encrypt PDF files created with Xojo. Continue reading and I will show you how.

Encrypting PDF files with PDFDocument is based in the use of the PDFPermissions class. You’ll need to create a new instance of the class passing along the “Owner” and “User” passwords. For example:

Var d As New PDFDocument
Var g As Graphics = d.Graphics

Var p As New PDFPermissions("OwnerPassword","UserPassword")

In addition, you can set other properties for the PDFPermissions instance; all of them are read/write and will be applied by the PDF viewer app for when the document is opened using the “user” password.

  • AllowCopyingContents is set to False by default. When set to True it will allow copying contents from the PDF, as for example the selected text or image.
  • AllowModifyingContents is set to False by default. When set to True it will all to modify the contents of the protected PDF document.
  • AllowPrinting is se to False by default. When it is set to True it will be possible to print the PDF.

Once the PDFPermissions instance has been created and the desired properties had been set, all you need to do is to assign such instance to the Permissions property for the PDFDocument instance you want to encrypt:

d.Permissions = p

Then, when it’s saving the document to a file, PDFDocument will encrypt all the streams of data containing sensitive information, as it can be the text or Images rendered on every one of the PDF pages plus the metadata information itself. The used encryption algorithm is AES 128 bits.

That’s all! You can distinguish an encrypted PDF file from an unencrypted one because, usually, the first one will be displayed with the image of a Lock in the icon. When you open an encrypted PDF in the viewer app you’ll be asked to type a password. If you enter the passord set to the “Owner” user, you’ll be able to do all the kind of operations allowed by the viewer app, while if you enter the “User” password, then the kind of options available will be determined by those set using the PDFPermissions properties.

Javier Menendez is an engineer at Xojo and has been using Xojo since 1998. He lives in Castellón, Spain and hosts regular Xojo hangouts en español. Ask Javier questions on Twitter at @XojoES or on the Xojo Forum.