[]
PDF security allows you to protect documents using encryption, passwords, and permissions. Encryption prevents unauthorized access to the document, while permissions control actions such as printing, editing, or copying content.
In DsPdfJS, document security is configured through the security property of PdfDocument. You can encrypt documents, set permissions, or configure a specific security handler that defines the encryption parameters.
You can encrypt a PDF document using the setEncryptOptions method. This method allows you to specify encryption settings such as the algorithm, key length, passwords, and permissions.
The following code example shows how to encrypt a PDF document.
// The recommended way to set PDF document encryption options is
// the PdfDocument.security.setEncryptionOptions() method.Using this method, you can specify:
// -) Encryption algorithm: AES(recommended) or RC4
// -) Encryption key length: 256 or 128 bits
// -) User and owner passwords
// -) Document permissions
// The options of this method are very similar to the security options you can
// select for a document in Acrobat.
const doc = new PdfDocument();
// set encryption options
doc.security.setEncryptOptions({
userPassword: "qwe",
encryptionLevel: EncryptionLevel.AES256,
})
// generate some document content
const page = doc.newPage();
const ctx = page.context;
// Render text using DrawString method
ctx.drawText("Encrypted document",
Font.getPdfFont(StandardPdfFont.TimesBold), 12, "Black", 72, 72);
// save the document
Util.saveFile("EncryptPDF.pdf", doc.savePdf());You can restrict actions such as printing, editing, or copying content by defining permissions when configuring document encryption.
Permissions are specified when setting encryption options or by configuring a security handler directly.
You can pass a permissions object to the setEncryptOptions method to restrict specific actions.
The following code example shows how to encrypt a PDF and configure document permissions.
const doc = new PdfDocument();
// set encryption options with permissions
doc.security.setEncryptOptions({
userPassword: "qwe",
encryptionLevel: EncryptionLevel.AES256,
permissions: {
ownerPassword: "abc",
copyContent: false,
editingPermissions: EditingPermissions.Disabled,
printingPermissions: PrintingPermissions.LowResolution
}
})
// generate some document content
const page = doc.newPage();
const ctx = page.context;
// Render text using DrawString method
ctx.drawText("Encrypted document with permissions",
Font.getPdfFont(StandardPdfFont.TimesBold), 12, "Black", 72, 72);
// save the document
Util.saveFile("EncryptPDFWithPermissions.pdf", doc.savePdf());Encryption parameters in a PDF document are defined by a security handler. When using the setEncryptOptions method, the library automatically creates a suitable security handler based on the provided options.
You can also create and configure a specific handler manually and assign it to the document.
The following code example shows how to encrypt a document using a specific security handler.
// According to the PDF specification, encryption parameters for a document
// are specified using a SecurityHandler object.You can read more about this in the PDF specification.
// The setEncryptionOptions() method demonstrated above internally creates a SecurityHandler
// object of the required type, initializes it according to the provided parameters,
// and assigns it to the PdfDocument.security.encryptHandler property.
// You can also do the same thing manually.The following example demonstrates this.
const doc = new PdfDocument();
// Encrypt the document using the oldest encryption handler.
// It supports only RC4 encryption with a 40-bit key length.
// This is a very old and insecure encryption algorithm, but
// you might have some legacy software that only supports this type of encryption.
const ssh = StandardSecurityHandlerRev2.create();
ssh.userPassword = "user";
// set securty handler
doc.security.encryptHandler = ssh;
// generate some document content
const page = doc.newPage();
const ctx = page.context;
// Render text using DrawString method
ctx.drawText("Document encrypted with security handler revision 2",
Font.getPdfFont(StandardPdfFont.TimesBold), 12, "Black", 72, 72);
// save the document
Util.saveFile("EncryptPDFWithSecurityHandler.pdf", doc.savePdf());When modifying an encrypted document, you may want to re‑encrypt it using the same encryption parameters. The decryption handler used to open the document can be cloned and assigned as the encryption handler when saving the modified document.
The following code example shows how to reuse the encryption parameters of an existing document.
// In some cases, it is necessary to modify an encrypted document and re-encrypt
// it using the same parameters.
// The following example demonstrates this.
// load the encrypted document
const doc = PdfDocument.load(await Util.loadFile("EncryptPDFWithPermissions.pdf"), "qwe");
// the doc.security.decryptHandler contains decryption parameters, used to load the document,
// log some properties:
const dh = doc.security.decryptHandler;
console.log(dh.constructor.name);
if (dh instanceof StandardSecurityHandlerRev6) {
console.log(`encryptionAlgorithm: ${dh.encryptionAlgorithm}`);
console.log(`encryptionKeyLength: ${dh.encryptionKeyLength}`);
}
// clone decryptHandler as assign as encryptHandler
doc.security.encryptHandler = dh.clone();
// set new passwords without it the document will be encryoted with empty password
doc.security.encryptHandler.userPassword = "user";
doc.security.encryptHandler.ownerPassword = "owner";
// generate some document content
const ctx = doc.pages.getAt(0).context;
// Render text using DrawString method
ctx.drawText("Document was edited",
Font.getPdfFont(StandardPdfFont.TimesBold), 12, "Red", 72, 100);
// save the document
Util.saveFile("ReuseEncryptHandler.pdf", doc.savePdf());In some cases, you may need to open an encrypted document without providing a password. DsPdfJS allows loading such documents by disabling password validation exceptions.
When a document is loaded this way, some operations may still be possible depending on the encryption configuration.
The following sections demonstrate common operations that can be performed.
You can add annotations to an encrypted document after loading it without enforcing password validation.
// load the encrypted document
const doc = PdfDocument.load(await Util.loadFile("EncryptPDFWithPermissions.pdf"), { throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// Set first page of PDF file as active page.
const page = doc.pages.getAt(0);
// Get page size.
const width = page.width;
const height = page.height;
// Add square annotation.
const sa = new SquareAnnotation();
sa.page = page;
/* Remove the UserName it is initialized by default and will cause an exception
when the document is saved because strings cannot be encrypted. */
sa.userName = null;
// Add square to the page.
sa.rect = { x: 10, y: 10, width: width - 20, height: height - 20 };
// Set color of the square.
sa.color = "Red";
// save the document
Util.saveFile("EncryptedAddAnnotation.pdf", doc.savePdf());You can read metadata values if the document metadata is not encrypted.
// load the encrypted document
const doc = PdfDocument.load(await Util.loadFile("EncryptPDFWithPermissions.pdf"), { throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// Check if the metadata is encrypted or not, and if not, change the metadata.
let encryptMetadata = true;
if (doc.security.encryptHandler instanceof StandardSecurityHandlerRev4)
encryptMetadata = doc.security.encryptHandler.encryptMetadata;
if (!encryptMetadata)
{
// Metadata is not encrypted.
const m = doc.metadata;
console.log("The document has not encrypted metadata:");
console.log(`CreatorTool: ${m.creatorTool}`);
console.log(`CreateDate : ${m.createDate}`);
}
else
{
Console.WriteLine("The document metadata is ENCRYPTED");
}If metadata is not encrypted, you can modify its values and save the updated document.
// load the encrypted document
const doc = PdfDocument.load(await Util.loadFile("EncryptPDFWithPermissions.pdf"), { throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// Check if the metadata is encrypted or not, and if not, change the metadata.
let encryptMetadata = true;
if (doc.security.encryptHandler instanceof StandardSecurityHandlerRev4)
encryptMetadata = doc.security.encryptHandler.encryptMetadata;
if (!encryptMetadata) {
// Metadata is not encrypted.
const m = doc.metadata;
console.log("The document has not encrypted metadata:");
console.log(`CreatorTool: ${m.creatorTool}`);
console.log(`CreateDate : ${m.createDate}`);
// Change the creator tool value.
m.creatorTool = "New value of CreatorTool";
Util.saveFile("EncryptedChangeMetadataValues.pdf", doc.savePdf());
}
else {
Console.WriteLine("The document metadata is ENCRYPTED");
}You can modify the page order of an encrypted document.
// load NOT encrypted PDF and encrypt it
const doc = PdfDocument.load(await Util.loadFile("Wetlands.pdf"));
doc.security.setEncryptOptions({ userPassword: "user" });
const encryptedDocData = doc.savePdf();
// load encrypted doc
const encDoc = PdfDocument.load(encryptedDocData, { throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// Swap the first and second pages.
encDoc.pages.swap(0, 1);
//
Util.saveFile("EncryptedChangePageOrder.pdf", encDoc.savePdf());You can update form field values in an encrypted document.
// load encrypted PDF and encrypt it
const doc = PdfDocument.load(await Util.loadFile("CheckBoxEncrypted.pdf"),
{ throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// change value
const fld = doc.acroForm.fields.getAt(0);
fld.value = "Off";
//
Util.saveFile("EncryptedChangeValueofCheckBoxField.pdf", doc.savePdf());You can retrieve information such as page count and page size from an encrypted document.
// load NOT encrypted PDF and encrypt it
const doc = PdfDocument.load(await Util.loadFile("Wetlands.pdf"));
doc.security.setEncryptOptions({ userPassword: "user" });
const encryptedDocData = doc.savePdf();
// load encrypted doc
const encDoc = PdfDocument.load(encryptedDocData, { throwExceptionIfInvalidPassword: false, throwExceptionIfUnsupportedSecurityOptions: false });
// Get the page count and size of the pages.
console.log(`Page count: ${encDoc.pages.count}`);
for (const page of encDoc.pages)
{
const sz = page.getRenderSize();
console.log(` Size of ${page.index} page: ${sz.width}x${sz.height}`);
}