Protect PDF
This guide will show you how to protect your PDF documents by adding a password. With UniPDF, you can encrypt a document against unauthorized access with UniPDF.
This example create a user password that grants limited access to the PDF document based on the permission levels and an owner password that grants full access to the PDF document.
The Check Permissions guide can be used to check the permissions of a PDF document. For unrestricted access to the PDF document, the user passoword should be left empty.
Before you begin
You should get your API key from your UniCloud account.
If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.
Project setup
Clone the project repository
In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.
git clone https://github.com/unidoc/unipdf-examples.git
Navigate to the security
folder in the unipdf-examples directory.
cd unipdf-examples/security
Configure environment variables
Replace the UNIDOC_LICENSE_API_KEY
with API credentials from your UniCloud account.
Linux/Mac
export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE
Windows
set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE
How it works
Lines 19-27
import the UniPDF packages and other required dependencies.
Lines 29-36
authenticate your request with your UNIDOC_LICENSE_API_KEY
with the init function.
The main function in lines 38-57
validates your input and passes them as arguments to the protectPdf
function.
Lines 59-107
define the protectPdf
function, which takes inputPath, outputPath, userPassword and ownerPassword as arguments. This is where you get to define the permssions
available to users.
The protectPdf
function checks to see if the input PDF has already been encrypted with pdfReader
, if not, it encrypts the document and writes the encrypted PDF document to the output path using pdfWriter
.
Run the code
Run this command to protect the PDF with password(s). This will also get all the required dependencies to run the program.
go run pdf_protect.go input.pdf <user-pass> <owner-pass> output.pdf
Sample output
The encrypted PDF will be saved to your currrent directory in the specified output path,output.pdf
. Open the encrypted PDF in any PDF viewer and use the user password or owner password to view its content.