How to flatten a PDF using JavaScript

Table of contents

    Whether you’re preparing PDFs for printing, ensuring viewer compatibility, or securing form data from edits, flattening PDFs is an essential operation. This tutorial shows you how to flatten PDF documents programmatically using JavaScript and Nutrient DWS Processor API.
    How to flatten a PDF using JavaScript
    Summary

    Flatten PDF documents using our flatten PDF JavaScript API. Create a free account, get API credentials, and implement flattening using Node.js with axios and form-data. Merge all layers — including annotations, form fields, and signatures — into a single non-editable layer for printing and secure distribution.

    This post shows how to flatten PDFs in JavaScript using the flatten PDF JavaScript API. The free plan includes 200 credits. Different operations consume different amounts of credits, so the number of PDFs you can process varies. Create a free account(opens in a new tab) to get your API key.

    Why flatten PDFs?

    Flattening PDFs is essential for document workflows that require finalized, non-editable outputs. Common use cases include:

    • Print preparation — Merge all layers — including annotations, form fields, and signatures — into a single layer to ensure printers render the complete document correctly.
    • Secure distribution — Lock completed forms to prevent recipients from modifying submitted data.
    • Archival compliance — Create immutable document versions for legal and regulatory requirements.
    • Consistent rendering — Guarantee documents appear identical across all systems and PDF readers.
    • Workflow automation — Process batches of documents programmatically as part of your backend infrastructure.

    Nutrient DWS Processor API

    Document flattening is one of 30+ PDF API tools. You can combine flattening with other tools to build document processing workflows:

    After creating your account, you can access all PDF API tools.

    Step 1 — Creating a free account on Nutrient

    Go to the signup page(opens in a new tab) to create your free account.

    Free account PSPDFKit API

    After creating your account, you’ll see your plan overview.

    Free plan PSPDFKit API

    The bottom-left corner shows your 200 starting credits and access to all PDF API tools.

    Step 2 — Obtaining the API key

    After verifying your email, get your API key from the dashboard. Click API keys in the left menu to see your keys overview.

    Flatten PDFs JavaScript API Key

    Copy the Live API key for the flatten PDF API.

    Step 3 — Setting up folders and files

    Create a folder called flatten_pdf and open it in your code editor. Create two subfolders: input_documents and processed_documents. Copy your PDF file to input_documents and rename it to document.pdf.

    Create a file called processor.js in the root folder for your code.

    Your folder structure:

    flatten_pdf
    ├── input_documents
    | └── document.pdf
    ├── processed_documents
    └── processor.js

    Step 4 — Installing dependencies

    Install these dependencies:

    Install both:

    npm install axios
    npm install form-data

    Step 5 — Writing the code

    Add this code to processor.js:

    const axios = require('axios');
    const FormData = require('form-data');
    const fs = require('fs');
    const formData = new FormData();
    formData.append(
    'instructions',
    JSON.stringify({
    parts: [
    {
    file: 'document',
    },
    ],
    actions: [
    {
    type: 'flatten',
    },
    ],
    }),
    );
    formData.append(
    'document',
    fs.createReadStream('input_documents/document.pdf'),
    );
    (async () => {
    try {
    const response = await axios.post(
    'https://api.pspdfkit.com/build',
    formData,
    {
    headers: formData.getHeaders({
    Authorization: 'Bearer YOUR_API_KEY_HERE',
    }),
    responseType: 'stream',
    },
    );
    response.data.pipe(
    fs.createWriteStream('processed_documents/result.pdf'),
    );
    } catch (e) {
    const errorString = await streamToString(e.response.data);
    console.log(errorString);
    }
    })();
    function streamToString(stream) {
    const chunks = [];
    return new Promise((resolve, reject) => {
    stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on('error', (err) => reject(err));
    stream.on('end', () =>
    resolve(Buffer.concat(chunks).toString('utf8')),
    );
    });
    }

    Replace YOUR_API_KEY_HERE with your API key.

    Code explanation

    The FormData variable contains the API instructions, and createReadStream reads the input PDF file. The POST request sends data to the flatten PDF API, and the API response saves to the processed_documents folder.

    Output

    Run the code:

    Terminal window
    node processor.js

    After successful execution, result.pdf appears in the processed_documents folder.

    Final folder structure:

    flatten_pdf
    ├── input_documents
    | └── document.pdf
    ├── processed_documents
    | └── result.pdf
    └── processor.js

    Conclusion

    You now know how to flatten PDFs in JavaScript using the flatten PDF API.

    Integrate these functions into your applications to flatten PDFs. The same API token works for other operations like merging documents and adding watermarks. Sign up(opens in a new tab) for a free trial.

    FAQ

    What happens when you flatten a PDF?

    Flattening merges all interactive and layered elements (form fields, annotations, signatures, transparency) into a single static layer. The resulting PDF appears identical but can no longer be edited — all content becomes part of the base document layer.

    Can I undo PDF flattening after processing?

    No. Flattening is a permanent operation. Once a PDF is flattened, you cannot restore the original editable form fields or layered annotations. Always keep a backup of your original document before flattening.

    Does flattening affect PDF file size?

    Flattening typically reduces file size slightly because it removes interactive layer data and form field metadata. However, the visual appearance remains identical to the original document.

    How many PDFs can I flatten with the free API account?

    The free account includes 200 credits. Each flatten operation consumes 0.5 credits, regardless of file size. This means you can flatten up to 400 PDFs with your free account. You can also combine flattening with other operations (like merging or watermarking) in a single API call.

    What Node.js version do I need to run this code?

    This code works with Node.js 14 and higher. It uses the axios and form-data npm packages, which are installed via npm. Verify your Node.js version with node --version.

    Can I use this code in a browser environment?

    No. This code is designed for Node.js server-side environments because it uses the fs module for file system operations. For browser-based PDF flattening, consider using Nutrient Web SDK instead.

    Jonathan D. Rhyne

    Jonathan D. Rhyne

    Co-Founder and CEO

    Jonathan joined PSPDFKit in 2014. As Co-founder and CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

    Explore related topics

    FREE TRIAL Ready to get started?