React Native Requires Chilkat v11.7.0+
React Native
Change the Passwords of an Encrypted PDF
See more PDF Protection Examples
Demonstrates the changePasswords operation, which gives an encrypted PDF new user and owner passwords and keeps its algorithm and permissions. The PDF is loaded with its current passwords, the two properties are then set to the new ones, and Protection reads them at the time of the call. Both passwords are replaced, so set both: a property left empty becomes an empty password.Chilkat React Native Downloads
import { JsonObject, Pdf } from '@chilkat/react-native'
function chilkatExample() {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// The PDF used in this example is available at encrypted_user_password.pdf
const pdf = new Pdf();
// Load with the current passwords.
pdf.userPassword = 'secret';
pdf.ownerPassword = 'owner-secret';
try {
pdf.loadFile('qa_data/pdf/encrypted_user_password.pdf');
} catch {
console.log(pdf.lastErrorText);
return;
}
// The new passwords. Protection reads the properties as they are when it is called.
pdf.userPassword = 'new-user-secret';
pdf.ownerPassword = 'new-owner-secret';
const json = new JsonObject();
const jsonOut = new JsonObject();
try {
pdf.protection('changePasswords', json, jsonOut);
} catch {
console.log(pdf.lastErrorText);
return;
}
// The algorithm and the permissions are kept.
console.log(`algorithm: ${jsonOut.stringOf('pending.algorithm')}`);
console.log(`password needed to open: ${jsonOut.boolOf('pending.userPasswordRequired')}`);
try {
pdf.writeFile('qa_output/minutes_new_passwords.pdf');
} catch {
console.log(pdf.lastErrorText);
return;
}
// The new user password opens the result.
const reader = new Pdf();
reader.userPassword = 'new-user-secret';
try {
reader.loadFile('qa_output/minutes_new_passwords.pdf');
} catch {
console.log(reader.lastErrorText);
return;
}
try {
reader.protection('getInfo', json, jsonOut);
} catch {
console.log(reader.lastErrorText);
return;
}
console.log(`with the new user password, opened with: ${jsonOut.stringOf('loaded.openedWith')}`);
// And so does the new owner password.
const owner = new Pdf();
owner.ownerPassword = 'new-owner-secret';
try {
owner.loadFile('qa_output/minutes_new_passwords.pdf');
} catch {
console.log(owner.lastErrorText);
return;
}
try {
owner.protection('getInfo', json, jsonOut);
} catch {
console.log(owner.lastErrorText);
return;
}
console.log(`with the new owner password, opened with: ${jsonOut.stringOf('loaded.openedWith')}`);
// Sample output:
// algorithm: rc4-128
// password needed to open: True
// with the new user password, opened with: user
// with the new owner password, opened with: owner
}