How to Remove PDF Password with JavaScript in NodeJS

Decrypt a PDF with its known open password from JavaScript in NodeJS and optionally delete sensitive resources afterward.
Share this page

This step-by-step guide demonstrates how to remove a known open password from a PDF from a NodeJS service through the Encrypt PDF API Tool. Along the way, we'll distinguish the JavaScript in NodeJS syntax from the Remove PDF Password API contract and show how its returned data supports the next step.

Why Remove PDF Password with JavaScript in NodeJS?

Authorized document automation sometimes receives encrypted PDFs that must be normalized before OCR, conversion, or extraction. Supplying the known open password creates a usable decrypted copy without modifying the protected source.

A NodeJS records service could accept password-protected reports from a partner, decrypt each report inside a controlled job, and then pass the output ID to indexing. The password remains an input to that job rather than becoming part of the PDF itself.

The endpoint only works when the current credential is valid. The sample also demonstrates optional resource deletion, which is important because both the encrypted upload and the unencrypted result can contain sensitive information.

JavaScript in NodeJS Code Example

// This request demonstrates how to decrypt a password-protected PDF by removing the password and requires that the current password be provided.
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');


// By default, we use the US-based API service. This is the primary endpoint for global use.
var apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//var apiUrl = "https://eu-api.pdfrest.com";



// Toggle deletion of sensitive files (default: false)
const DELETE_SENSITIVE_FILES = false;

// Create a new form data instance and append the PDF file and parameters to it
var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('current_open_password', 'current_example_pw');
data.append('output', 'pdfrest_decrypted_pdf');

// Define configuration options for axios request
var config = {
  method: 'post',
  maxBodyLength: Infinity, // Set maximum length of the request body
  url: apiUrl + '/decrypted-pdf',
  headers: {
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key
    ...data.getHeaders() // Set headers with form data headers
  },
  data : data // Add headers to the request
};

// Send request and handle response or error
axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));

  // All files uploaded or generated are automatically deleted based on the
  // File Retention Period as shown on https://pdfrest.com/pricing.
  // For immediate deletion of files, particularly when sensitive data
  // is involved, an explicit delete call can be made to the API.
  //
  // Deletes all files in the workflow, including outputs. Save all desired files before enabling this step.

  var body = response.data;
  var input_id = body.inputId;
  var result_id = body.outputId;
    var delete_config = {
      method: 'post',
      maxBodyLength: Infinity,
      url: apiUrl + '/delete',
      headers: {
        'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'Content-Type': 'application/json'
      },
      data: { ids: input_id + ', ' + result_id }
    };

  if (DELETE_SENSITIVE_FILES) {
    axios(delete_config)
      .then(function (delete_response) { console.log(JSON.stringify(delete_response.data)); })
      .catch(function (error) { console.log(error); });
  }

})
  .catch(function (error) {
    console.log(error);
  });

// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample

Source for Remove PDF Password: View the JavaScript in NodeJS sample on GitHub.

Breaking Down the Code

Load the NodeJS request and file modules

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');

Axios sends the HTTP calls for Remove PDF Password, FormData constructs multipart bodies when needed, and Node's fs module opens local files as streams. Together, these packages provide the transport and file handling required by the JavaScript Remove PDF Password sample.

Select the pdfRest service region

// By default, we use the US-based API service. This is the primary endpoint for global use.
var apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//var apiUrl = "https://eu-api.pdfrest.com";

apiUrl centralizes regional routing for Remove PDF Password. The NodeJS Remove PDF Password flow can switch to the documented EU hostname without changing the endpoint paths that follow.

Add the PDF, current password, and output name

var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('current_open_password', 'current_example_pw');
data.append('output', 'pdfrest_decrypted_pdf');

// Define configuration options for axios request

This block constructs the operation-specific input for Remove PDF Password. Its file parts carry binary content, while the named Remove PDF Password fields describe pdfRest behavior rather than syntax supplied by JavaScript in NodeJS.

Configure and submit the decrypt request

var config = {
  method: 'post',
  maxBodyLength: Infinity, // Set maximum length of the request body
  url: apiUrl + '/decrypted-pdf',
  headers: {
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key
    ...data.getHeaders() // Set headers with form data headers
  },
  data : data // Add headers to the request
};

// Send request and handle response or error
axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));

  // All files uploaded or generated are automatically deleted based on the
  // File Retention Period as shown on https://pdfrest.com/pricing.
  // For immediate deletion of files, particularly when sensitive data

The JavaScript in NodeJS request joins the Remove PDF Password endpoint, authentication header, and prepared body. For this Remove PDF Password call, the multipart metadata generated by JavaScript in NodeJS must remain paired with the body so pdfRest can separate files from options.

Optionally delete sensitive inputs and outputs

if (DELETE_SENSITIVE_FILES) {
    axios(delete_config)
      .then(function (delete_response) { console.log(JSON.stringify(delete_response.data)); })
      .catch(function (error) { console.log(error); });
  }

})
  .catch(function (error) {
    console.log(error);
  });

// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample

The optional JavaScript in NodeJS cleanup path collects the sensitive input and output IDs and sends them to Delete Files. Enable this Remove PDF Password cleanup only after the JavaScript in NodeJS application has preserved every result it needs.

Beyond the Tutorial

This walkthrough gives you an authorized JavaScript in NodeJS path from a password-protected source to a decrypted PDF resource that downstream tools can use.

Provide the password through a secret-management path and avoid printing the multipart body or request configuration. Save necessary output before enabling deletion, since the cleanup call intentionally removes the generated file as well as the source.

Try the Remove PDF Password workflow with a representative file in API Lab, then adapt the request in JavaScript in NodeJS. The Encrypt PDF API Tool documentation provides the complete JavaScript in NodeJS context for Remove PDF Password values, defaults, and limitations.

Note: This JavaScript in NodeJS Remove PDF Password tutorial uses a multipart file upload. For Remove PDF Password content already stored in pdfRest, the JavaScript in NodeJS JSON payload example supplies a managed resource ID instead of uploading the file again.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.