Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.7.0+

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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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

  final pdf = CkPdf();

  // Load with the current passwords.
  pdf.userPassword = 'secret';
  pdf.ownerPassword = 'owner-secret';
  try {
    pdf.loadFile('qa_data/pdf/encrypted_user_password.pdf');
  } on ChilkatException catch (e) {
    print(e.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';

  final json = CkJsonObject();
  final jsonOut = CkJsonObject();
  try {
    pdf.protection('changePasswords', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // The algorithm and the permissions are kept.
  print('algorithm: ${jsonOut.stringOf('pending.algorithm')}');
  print('password needed to open: ${jsonOut.boolOf('pending.userPasswordRequired')}');

  try {
    pdf.writeFile('qa_output/minutes_new_passwords.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // The new user password opens the result.
  final reader = CkPdf();
  reader.userPassword = 'new-user-secret';
  try {
    reader.loadFile('qa_output/minutes_new_passwords.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    reader.protection('getInfo', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('with the new user password, opened with: ${jsonOut.stringOf('loaded.openedWith')}');

  // And so does the new owner password.
  final owner = CkPdf();
  owner.ownerPassword = 'new-owner-secret';
  try {
    owner.loadFile('qa_output/minutes_new_passwords.pdf');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    owner.protection('getInfo', json, jsonOut);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('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
}