How to Flatten PDF Layers with JavaScript in NodeJS

Use JavaScript in NodeJS to flatten PDF layers and deliver a stable page appearance without optional-content controls.
Share this page

Follow this JavaScript in NodeJS walkthrough to flatten PDF layers with the Flatten Layers API Tool. You'll see the complete Flatten PDF Layers sample first, then examine the transport code and API fields that matter when this JavaScript in NodeJS pattern moves into an application.

Why Flatten PDF Layers with JavaScript in NodeJS?

Optional-content groups allow one PDF to contain several visual configurations, but not every viewer or downstream system handles those controls consistently. Flatten Layers produces a consolidated PDF whose displayed content is fixed.

Consider a NodeJS document service that prepares layered site maps for contractors. It can flatten the customer-approved combination of utilities, labels, and boundaries before the file enters a download queue, avoiding surprises in lightweight viewers.

The endpoint uses the visibility state already present in the source; it does not accept a separate list of layers to turn on or off. Applications should establish and verify the intended view before they submit the document.

JavaScript in NodeJS Code Example

/**
 * This request demonstrates how to flatten layers in a PDF.
 */
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";

// 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("output", "pdfrest_flattened_layers_pdf");

// define configuration options for axios request
var config = {
  method: "post",
  maxBodyLength: Infinity, // set maximum length of the request body
  url: apiUrl + "/flattened-layers-pdf",
  headers: {
    "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
    ...data.getHeaders(), // set headers for the request
  },
  data: data, // set the data to be sent with the request
};

// send request and handle response or error
axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .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 Flatten PDF Layers: 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 Flatten PDF Layers, 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 Flatten PDF Layers 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";

// Create a new form data instance and append the PDF file and parameters to it

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

Add the source and output fields

var data = new FormData();
data.append("file", fs.createReadStream("/path/to/file"));
data.append("output", "pdfrest_flattened_layers_pdf");

// define configuration options for axios request
var config = {

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

Configure the Axios request

var config = {
  method: "post",
  maxBodyLength: Infinity, // set maximum length of the request body
  url: apiUrl + "/flattened-layers-pdf",
  headers: {
    "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
    ...data.getHeaders(), // set headers for the request
  },
  data: data, // set the data to be sent with the request
};

// send request and handle response or error
axios(config)
  .then(function (response) {

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

Handle the generated PDF response

axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .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 final Flatten PDF Layers handling in JavaScript in NodeJS exposes the HTTP result and JSON body. Before using a Flatten PDF Layers output or request ID, production JavaScript in NodeJS code should verify the status and retain the identifier required by the next step.

Beyond the Tutorial

You now have a JavaScript in NodeJS pattern for turning the approved visible layer state into a stable PDF that no longer depends on optional-content controls.

Retain the layered source beside the generated delivery copy when alternate views remain valuable. A preview comparison is especially useful for maps and design assets, where an omitted layer can carry operational meaning even when the request itself succeeds.

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

Note: This JavaScript in NodeJS Flatten PDF Layers tutorial uses a multipart file upload. For Flatten PDF Layers 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.