---
title: "How to merge PDFs using JavaScript"
canonical_url: "https://www.nutrient.io/blog/how-to-merge-pdfs-using-javascript/"
md_url: "https://www.nutrient.io/blog/how-to-merge-pdfs-using-javascript.md"
last_updated: "2026-08-20T22:12:21.734Z"
description: "Merge PDF documents programmatically using JavaScript and Nutrient DWS Processor API. Step-by-step tutorial with code examples and free API credits."
---

**TL;DR**

Merge multiple PDF files using our merge PDF JavaScript API. Create a free account, get API credentials, and implement merging using Node.js with axios and form-data. Combine with 30+ other API tools for document processing workflows.

In this post, you’ll learn how to combine multiple PDF files using our [merge PDF JavaScript API](https://www.nutrient.io/api/merge-pdf-api/). With our API, you receive 50 credits with the free plan. Different operations on a document consume different amounts of credits, so the number of PDF documents you can generate may vary. You’ll just need to create a [free account](https://dashboard.nutrient.io/sign_up/?product=processor) to get access to your API key.

## Nutrient DWS Processor API

Document merging is just one of our 30+ [PDF API tools](https://www.nutrient.io/api/). You can combine our merging tool with other tools to create complex document processing workflows, such as:

- Converting MS Office files and images into PDFs before merging

- Performing OCR on several documents before merging

- Merging, watermarking, and flattening PDFs

Once you create your account, you’ll be able to access all our PDF API tools.

## Step 1 — Creating a free account on Nutrient

Go to our [website](https://dashboard.nutrient.io/sign_up/?product=processor), where you’ll see the page below, prompting you to create your free account.![Free account Nutrient DWS Processor API](@/assets/images/blog/2022/how-to-merge-pdfs-using-python/image4.png)

Once you’ve created your account, you’ll be welcomed by the page below, which shows an overview of your plan details.![Free plan Nutrient DWS Processor API](@/assets/images/blog/2022/how-to-merge-pdfs-using-python/image1.png)

As you can see in the bottom-left corner, you’ll start with 50 credits to process, and you’ll be able to access all our PDF API tools.

Copy the **Live API key**, because you’ll need this for the merge PDF API.

## Step 2 — Setting up files and folders

Now, create a folder called `merge_pdf` and open it in a code editor. For this tutorial, you’ll use VS Code as your primary code editor. Next, create two folders inside `merge_pdf` and name them `input_documents` and `processed_documents`.

Then, in the root folder, `merge_pdf`, create a file called `processor.js`. This is where you’ll keep your code.

## Step 3 — Installing dependencies

To get started merging PDF pages, you first need to install the following dependencies:

- [axios](https://www.npmjs.com/package/axios) — This package is used for making REST API calls.

- [Form-Data](https://www.npmjs.com/package/form-data) — This package is used for creating form data.

Use the commands below to install both of them:

```bash

npm install form-data

```

```bash

npm install axios

```

## Step 4 — Writing the code

Now, open the `processor.js` file and paste the code below into it:

```js

// This code requires Node.js. Do not run this code directly in a web browser.

const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

const formData = new FormData();
formData.append(
  "instructions",
  JSON.stringify({
    parts: [
      {
        file: "first_half",
      },
      {
        file: "second_half",
      },
    ],
  }),
);
formData.append(
  "first_half",
  fs.createReadStream("input_documents/first_half.pdf"),
);
formData.append(
  "second_half",
  fs.createReadStream("input_documents/second_half.pdf"),
);

(async () => {
  try {
    const response = await axios.post(
      "https://api.nutrient.io/build",
      formData,
      {
        headers: formData.getHeaders({
          Authorization: "Bearer YOUR_API_KEY_HERE",
        }),
        responseType: "stream",
      },
    );

    response.data.pipe(
      fs.createWriteStream("processed_documents/node_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")));
  });
}

```

Make sure to replace `YOUR_API_KEY_HERE` with your API key.

### Code explanation

You first imported all the packages needed to make the API call, and then you prepared the `FormData`. After that, you appended the `first_half` and `second_half` by reading the `first_half.pdf` and `second_half.pdf` files from the `input_documents` folder.

You then made an asynchronous API call to the merge PDF API and stored the result in `processed_documents/node_result.pdf`.

## Step 5 — Output

To run the code, use the command below:

```bash

node processor.js

```

On the successful execution of the code, you’ll see a new processed file named `node_result.pdf` in the `processed_documents` folder.

The folder structure will look like this:

```

merge_pdf
├── input_documents
|    └── first_half.pdf
|    └── second_half.pdf
├── node_modules
├── processed_documents
|    └── node_result.pdf

```

You can now easily integrate this function into your other JavaScript modules and merge different documents.

## Conclusion

In this post, you learned how to merge files for your JavaScript application into a single PDF using our merge PDF API.

If you have a more complex use case, you can use our other tools to add watermarks, perform OCR, and edit (split, flatten, delete, duplicate) documents — and you can even combine these tools. To get started with a free trial, [sign up here](https://dashboard.nutrient.io/sign_up/?product=processor).

## Additional resources

Explore more ways to work with Nutrient API:

- **[Postman collection](https://www.nutrient.io/guides/dws-processor/getting-started/postman-collection.md)** — Test API endpoints directly in Postman

- **[Zapier integration](https://www.nutrient.io/guides/dws-processor/getting-started/zapier-integration.md)** — Automate document workflows without code

- **[MCP Server](https://www.nutrient.io/api/mcp-server-pdf-automation-llm/)** — PDF automation for LLM applications

- **[JavaScript client](https://www.nutrient.io/guides/dws-processor/supported-languages/javascript.md)** — Official JavaScript library

## FAQ

#### What else can I do with Nutrient DWS Processor API besides merging PDFs?

Nutrient DWS Processor API offers 30+ PDF operations, including splitting, watermarking, OCR, flattening, and converting Office documents to PDF. You can combine these operations in a single workflow. For example, merge multiple PDFs, watermark the result, then flatten it to prevent editing — all through the same API.

#### Can I use this in a web browser or only in Node.js?

This code is designed for Node.js only, as indicated by the comment in the code. It uses Node.js modules like `fs` (file system) and `FormData` that aren’t available in web browsers. For browser-based PDF merging, you’ll need to implement a server-side endpoint that handles the API call, or use Nutrient’s client-side SDK for in-browser PDF operations.

#### How do I handle errors when merging fails?

The code example includes error handling with a try-catch block. When an error occurs, the `streamToString` function converts the error response into a readable string and logs it. Common errors include invalid API keys, missing files, or malformed instructions. Check the error message for specific details, and ensure your API key is correct and files exist in the specified paths.

#### What file formats can I merge besides PDF?

The Nutrient DWS Processor API can convert various formats to PDF before merging, including MS Office documents (Word, Excel, PowerPoint) and images (JPEG, PNG, TIFF). First convert documents to PDF using the [API’s conversion tools](https://www.nutrient.io/api/converter-api/), and then merge them. This enables you to combine mixed document types into a single PDF output.

#### How do I merge PDFs from URLs instead of local files?

Instead of using `fs.createReadStream()` with local file paths, you can fetch remote PDFs and append them as buffers or streams. Use `axios` to download the PDF, and then append the response data to `FormData`. For example: `const response = await axios.get(url, {responseType: 'stream'})`, then `formData.append('file', response.data)`. This allows merging PDFs from remote servers without saving them locally first.
---

## Related pages

- [The business case for accessibility: Five ways it drives enterprise value](/blog/5-ways-accessibility-drives-enterprise-value.md)
- [Accessibility Untangled Why It Matters Guide](/blog/accessibility-untangled-why-it-matters-guide.md)
- [Advanced Techniques For React Native Ui Components](/blog/advanced-techniques-for-react-native-ui-components.md)
- [`vector_store` holds your indexed documents (see the multimodal RAG post](/blog/agentic-rag.md)
- [Ai Document Automation Extraction To Action](/blog/ai-document-automation-extraction-to-action.md)
- [Ai Legal Assistant Document Authoring](/blog/ai-legal-assistant-document-authoring.md)
- [Start (clears any prior buffer), navigate the document, then stop into a file.](/blog/android-faster-pdf-rendering.md)
- [Android Pdf Out Of Memory Handling](/blog/android-pdf-out-of-memory-handling.md)
- [Angular File Viewer Pdf Image Office Files](/blog/angular-file-viewer-pdf-image-office-files.md)
- [Auto Tagging And Document Accessibility In Dotnet Sdk](/blog/auto-tagging-and-document-accessibility-in-dotnet-sdk.md)
- [Best Document Ai Platforms](/blog/best-document-ai-platforms.md)
- [Best Document Viewers](/blog/best-document-viewers.md)
- [Build Vs Buy Document Extraction](/blog/build-vs-buy-document-extraction.md)
- [The CEO’s AI playbook: Why decision architecture beats model selection](/blog/ceo-ai-playbook-decision-architecture.md)
- [1. Extract and chunk the PDF.](/blog/chat-with-pdf.md)
- [Complete Guide To Pdfjs](/blog/complete-guide-to-pdfjs.md)
- [Construction Document Data Extraction](/blog/construction-document-data-extraction.md)
- [Convert One Drive Files To Pdf In Sharepoint](/blog/convert-one-drive-files-to-pdf-in-sharepoint.md)
- [Create And Edit Pdfs In Flutter](/blog/create-and-edit-pdfs-in-flutter.md)
- [Create Pdfs With React](/blog/create-pdfs-with-react.md)
- [Creating A Document Scanner With Ocr In Python](/blog/creating-a-document-scanner-with-ocr-in-python.md)
- [Creating And Filling Pdf Forms Programmatically In Javascript](/blog/creating-and-filling-pdf-forms-programmatically-in-javascript.md)
- [The CTO’s AI playbook: Why accountability architecture beats orchestration](/blog/cto-ai-playbook-accountability-architecture.md)
- [Digital Signatures](/blog/digital-signatures.md)
- [Digital Workflow Automation](/blog/digital-workflow-automation.md)
- [Document Ai Vs Ocr](/blog/document-ai-vs-ocr.md)
- [Document Extraction Confidence Scores](/blog/document-extraction-confidence-scores.md)
- [Document Viewer](/blog/document-viewer.md)
- [Document Watermarking](/blog/document-watermarking.md)
- [Emerging threats: Your logging system may be an agentic threat vector](/blog/emerging-threats-your-logging-system.md)
- [Extract Patient Data On Premises](/blog/extract-patient-data-on-premises.md)
- [app.py](/blog/extract-text-from-pdf-using-python.md)
- [Fillable Pdf](/blog/fillable-pdf.md)
- [How To Add Digital Signature To Pdf Using React](/blog/how-to-add-digital-signature-to-pdf-using-react.md)
- [How To Build A Dotnet Maui Pdf Viewer](/blog/how-to-build-a-dotnet-maui-pdf-viewer.md)
- [How To Build A Flutter Pdf Viewer](/blog/how-to-build-a-flutter-pdf-viewer.md)
- [or](/blog/how-to-build-a-javascript-pdf-viewer-with-pdfjs.md)
- [How To Build A Javascript Pdf Viewer](/blog/how-to-build-a-javascript-pdf-viewer.md)
- [or](/blog/how-to-build-a-nextjs-pdf-viewer.md)
- [How To Build A Powerpoint Viewer Using Javascript](/blog/how-to-build-a-powerpoint-viewer-using-javascript.md)
- [Using Yarn](/blog/how-to-build-a-react-excel-viewer.md)
- [How To Build A React Native Pdf Viewer](/blog/how-to-build-a-react-native-pdf-viewer.md)
- [How To Build A React Powerpoint Viewer](/blog/how-to-build-a-react-powerpoint-viewer.md)
- [How To Build A Reactjs File Viewer](/blog/how-to-build-a-reactjs-file-viewer.md)
- [or](/blog/how-to-build-a-reactjs-pdf-viewer-with-react-pdf.md)
- [or](/blog/how-to-build-a-reactjs-pdf-viewer.md)
- [How To Build A Reactjs Viewer With Pdfjs](/blog/how-to-build-a-reactjs-viewer-with-pdfjs.md)
- [How To Build A Vuejs Pdf Viewer With Pdfjs](/blog/how-to-build-a-vuejs-pdf-viewer-with-pdfjs.md)
- [How To Build A Vuejs Pdf Viewer](/blog/how-to-build-a-vuejs-pdf-viewer.md)
- [How To Build An Android Pdf Viewer](/blog/how-to-build-an-android-pdf-viewer.md)
- [How To Build An Angular Pdf Viewer With Ng2 Pdf Viewer](/blog/how-to-build-an-angular-pdf-viewer-with-ng2-pdf-viewer.md)
- [How To Build An Angular Pdf Viewer With Pdfjs](/blog/how-to-build-an-angular-pdf-viewer-with-pdfjs.md)
- [How To Convert Docx To Pdf Using Javascript](/blog/how-to-convert-docx-to-pdf-using-javascript.md)
- [How To Convert Docx To Pdf Using Python](/blog/how-to-convert-docx-to-pdf-using-python.md)
- [How To Convert Html To Pdf Using Html2pdf](/blog/how-to-convert-html-to-pdf-using-html2pdf.md)
- [or](/blog/how-to-convert-html-to-pdf-using-react.md)
- [How To Convert Html To Pdf Using Wkhtmltopdf And Csharp](/blog/how-to-convert-html-to-pdf-using-wkhtmltopdf-and-csharp.md)
- [or](/blog/how-to-convert-html-to-pdf-using-wkhtmltopdf-and-python.md)
- [How To Convert Word To Pdf In Nodejs](/blog/how-to-convert-word-to-pdf-in-nodejs.md)
- [or](/blog/how-to-create-a-react-js-signature-pad.md)
- [How To Create Pdfs With React To Pdf](/blog/how-to-create-pdfs-with-react-to-pdf.md)
- [How To Edit Pdfs Using Ios Pdf Library](/blog/how-to-edit-pdfs-using-ios-pdf-library.md)
- [How To Embed A Pdf Viewer In Your Website](/blog/how-to-embed-a-pdf-viewer-in-your-website.md)
- [How To Extract Tables From Pdf And Images](/blog/how-to-extract-tables-from-pdf-and-images.md)
- [How To Generate Pdf From Html With Nodejs](/blog/how-to-generate-pdf-from-html-with-nodejs.md)
- [base_url tells WeasyPrint where to resolve relative asset paths](/blog/how-to-generate-pdf-reports-from-html-in-python.md)
- [How To Ocr Pdfs In Linux](/blog/how-to-ocr-pdfs-in-linux.md)
- [How To Print Pdf In Csharp](/blog/how-to-print-pdf-in-csharp.md)
- [Open an image.](/blog/how-to-use-tesseract-ocr-in-python.md)
- [From an HTML string.](/blog/html-in-pdf-format.md)
- [Html To Pdf In Javascript](/blog/html-to-pdf-in-javascript.md)
- [Javascript Pdf Editors](/blog/javascript-pdf-editors.md)
- [Javascript Pdf Libraries](/blog/javascript-pdf-libraries.md)
- [Linearized Pdf](/blog/linearized-pdf.md)
- [or](/blog/merge-pdfs.md)
- [Swift Package Manager](/blog/mobile-pdf-sdk.md)
- [`elements` come from your document parser — each has a type and content.](/blog/multimodal-rag.md)
- [Nutrient Flutter 6 Bindings Api](/blog/nutrient-flutter-6-bindings-api.md)
- [Nutrient Vs Conga Composer](/blog/nutrient-vs-conga-composer.md)
- [Online Document Viewer](/blog/online-document-viewer.md)
- [Open Pdf In Your Web App](/blog/open-pdf-in-your-web-app.md)
- [Building WCAG 2.2, Section 508, and PDF/UA-compliant PDFs with an SDK](/blog/pdf-accessibility.md)
- [Extract data from PDF files: A developer guide to structured data from PDFs and scans](/blog/pdf-data-extraction-developer-guide.md)
- [Pdf Extraction Benchmark Opendataloader Bench](/blog/pdf-extraction-benchmark-opendataloader-bench.md)
- [Pdf Extraction Document Case Studies](/blog/pdf-extraction-document-case-studies.md)
- [Pdf Page Labels](/blog/pdf-page-labels.md)
- [Pdf Sdk Compliance Security Checklist](/blog/pdf-sdk-compliance-security-checklist.md)
- [Pdf Sdk Performance Benchmark](/blog/pdf-sdk-performance-benchmark.md)
- [Pdf Ua Compliance Guide](/blog/pdf-ua-compliance-guide.md)
- [Pdfjs Accessibility Structtree Printing](/blog/pdfjs-accessibility-structtree-printing.md)
- [Pdfjs Advanced Loading Streaming Workers](/blog/pdfjs-advanced-loading-streaming-workers.md)
- [Pdfjs Annotation Editor Layer](/blog/pdfjs-annotation-editor-layer.md)
- [Pdfjs Area Annotations Canvas Capture](/blog/pdfjs-area-annotations-canvas-capture.md)
- [Pdfjs Coordinate Systems Pdf To Screen](/blog/pdfjs-coordinate-systems-pdf-to-screen.md)
- [Pdfjs Document Outline Bookmarks Metadata](/blog/pdfjs-document-outline-bookmarks-metadata.md)
- [Pdfjs Eventbus Guide](/blog/pdfjs-eventbus-guide.md)
- [macOS](/blog/pdfjs-file-format-conversion-to-pdf.md)
- [macOS](/blog/pdfjs-generating-pdf-thumbnails-pdf2pic.md)
- [Pdfjs Limitations Commercial Upgrade](/blog/pdfjs-limitations-commercial-upgrade.md)
- [Pdfjs Native Annotation Layer Forms](/blog/pdfjs-native-annotation-layer-forms.md)
- [Pdfjs Navigation Zoom Rotation](/blog/pdfjs-navigation-zoom-rotation.md)
- [Pdfjs Pdf Page Manipulation Pdf Lib](/blog/pdfjs-pdf-page-manipulation-pdf-lib.md)
- [Pdfjs React Viewer Setup](/blog/pdfjs-react-viewer-setup.md)
- [Pdfjs Rendering Overlays React Portals](/blog/pdfjs-rendering-overlays-react-portals.md)
- [Pdfjs Server Side Text Extraction](/blog/pdfjs-server-side-text-extraction.md)
- [Pdfjs Sticky Note Annotations](/blog/pdfjs-sticky-note-annotations.md)
- [Pdfjs Text Highlight Annotations](/blog/pdfjs-text-highlight-annotations.md)
- [Pdfjs Text Search Pdffindcontroller](/blog/pdfjs-text-search-pdffindcontroller.md)
- [Pdfjs Thumbnail Sidebar](/blog/pdfjs-thumbnail-sidebar.md)
- [Process Flows](/blog/process-flows.md)
- [React Native Pdf Annotation](/blog/react-native-pdf-annotation.md)
- [Using Yarn](/blog/react-pdf-editor.md)
- [React Pdf Setup Basic Rendering](/blog/react-pdf-setup-basic-rendering.md)
- [or](/blog/sample-blog-updated.md)
- [Sdk Product Updates Q2 2026](/blog/sdk-product-updates-q2-2026.md)
- [Add DWS MCP Server to your Claude Code project.](/blog/teaching-llms-to-read-pdfs.md)
- [Open an image file.](/blog/tesseract-python-guide.md)
- [Define the HTML part of the document.](/blog/top-10-ways-to-generate-pdfs-in-python.md)
- [Top 5 Javascript Pdf Viewers](/blog/top-5-javascript-pdf-viewers.md)
- [or](/blog/top-js-pdf-libraries.md)
- [Convert an HTML file to PDF.](/blog/top-ten-ways-to-convert-html-to-pdf.md)
- [Vector Pdf](/blog/vector-pdf.md)
- [Wcag2 Accessibility Requirements Documents](/blog/wcag2-accessibility-requirements-documents.md)
- [Web Sdk Is Now Headless](/blog/web-sdk-is-now-headless.md)
- [What Are Annotations](/blog/what-are-annotations.md)
- [What Is A Vpat](/blog/what-is-a-vpat.md)
- [What Is Document Processing](/blog/what-is-document-processing.md)
- [What Is Intelligent Document Processing](/blog/what-is-intelligent-document-processing.md)
- [What Is Pdf Ua](/blog/what-is-pdf-ua.md)
- [Why Pdfium Is A Trusted Platform For Pdf Rendering](/blog/why-pdfium-is-a-trusted-platform-for-pdf-rendering.md)
- [Why Your Ai Agent Hallucinates Pdf Table Data](/blog/why-your-ai-agent-hallucinates-pdf-table-data.md)

