How to Merge Different File Formats Together as a PDF with JavaScript in NodeJS

Build a NodeJS workflow that converts mixed file types to PDF and merges the resulting resources into one document.
Share this page

Learn how to convert different file formats and merge them as one PDF using JavaScript in NodeJS and the Merge PDFs API Tool. This Merge Different Formats Together as a PDF tutorial keeps the official sample intact and breaks down authentication, payload construction, endpoint behavior, and result handling for JavaScript in NodeJS.

Why Merge Different File Formats Together as a PDF with JavaScript in NodeJS?

Applications frequently need to assemble a single PDF from source files that cannot be merged directly. A conversion stage normalizes each image, presentation, or office document before Merge PDFs combines the results.

A NodeJS onboarding service might collect an identity image and a presentation-style orientation guide. By retaining the outputId from each /pdf response, it can submit both managed resources to /merged-pdf in the desired sequence.

The nested promise chain in the sample enforces the dependency between steps: presentation conversion starts after image conversion, and merging starts only after both IDs exist. A production service may express the same dependency with async/await.

JavaScript in NodeJS Code Example

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

/* In this sample, we will show how to merge different file types together as
* discussed in https://pdfrest.com/solutions/merge-multiple-types-of-files-together/.
First, we will upload an image file to the /pdf route and capture the output ID.
* Next, we will upload a PowerPoint file to the /pdf route and capture its output
* ID. Finally, we will pass both IDs to the /merged-pdf route to combine both inputs
* into a single PDF.
*
* Note that there is nothing special about an image and a PowerPoint file, and
* this sample could be easily used to convert and combine any two file types
* that the /pdf route takes as inputs.
*/

// 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";

var apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your API key

var imageData = new FormData();
imageData.append("file", fs.createReadStream("/path/to/image.png"));

var imageConfig = {
  method: "post",
  maxBodyLength: Infinity,
  url: apiUrl + "/pdf",
  headers: {
    "Api-Key": apiKey,
    ...imageData.getHeaders(),
  },
  data: imageData,
};

axios(imageConfig)
  .then(function (response) {
    var imagePDFID = response.data.outputId;

    var pptData = new FormData();
    pptData.append("file", fs.createReadStream("/path/to/powerpoint.ppt"));

    var pptConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: apiUrl + "/pdf",
      headers: {
        "Api-Key": apiKey,
        ...pptData.getHeaders(),
      },
      data: pptData,
    };

    axios(pptConfig)
      .then(function (response) {
        var pptPDFID = response.data.outputId;

        var mergeData = new FormData();
        mergeData.append("id", imagePDFID);
        mergeData.append("pages[]", "1-last");
        mergeData.append("type[]", "id");
        mergeData.append("id", pptPDFID);
        mergeData.append("pages[]", "1-last");
        mergeData.append("type[]", "id");
        mergeData.append("output", "pdfrest_merged_pdf");

        var mergeConfig = {
          method: "post",
          maxBodyLength: Infinity,
          url: apiUrl + "/merged-pdf",
          headers: {
            "Api-Key": apiKey,
            ...mergeData.getHeaders(),
          },
          data: mergeData,
        };

        axios(mergeConfig)
          .then(function (response) {
            console.log(JSON.stringify(response.data)); // If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample
          })
          .catch(function (error) {
            console.log(error);
          });
      })
      .catch(function (error) {
        console.log(error);
      });
  })
  .catch(function (error) {
    console.log(error);
  });

Source for Merge Different Formats Together as a PDF: 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 Merge Different Formats Together as a PDF, 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 Merge Different Formats Together as a PDF 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";

var apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your API key

apiUrl centralizes regional routing for Merge Different Formats Together as a PDF. The NodeJS Merge Different Formats Together as a PDF flow can switch to the documented EU hostname without changing the endpoint paths that follow.

Convert the image and capture its ID

var imageData = new FormData();
imageData.append("file", fs.createReadStream("/path/to/image.png"));

var imageConfig = {
  method: "post",
  maxBodyLength: Infinity,
  url: apiUrl + "/pdf",
  headers: {
    "Api-Key": apiKey,
    ...imageData.getHeaders(),
  },
  data: imageData,
};

axios(imageConfig)
  .then(function (response) {
    var imagePDFID = response.data.outputId;

The first JavaScript in NodeJS conversion sends the image to /pdf and captures its outputId. That ID becomes the first Merge Different Formats Together as a PDF input without an intermediate download back to JavaScript in NodeJS.

Convert the presentation after the first response

var pptData = new FormData();
    pptData.append("file", fs.createReadStream("/path/to/powerpoint.ppt"));

    var pptConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: apiUrl + "/pdf",
      headers: {
        "Api-Key": apiKey,
        ...pptData.getHeaders(),
      },
      data: pptData,
    };

    axios(pptConfig)
      .then(function (response) {
        var pptPDFID = response.data.outputId;

The second JavaScript in NodeJS conversion repeats the normalization step for the presentation. The Merge Different Formats Together as a PDF workflow must receive this presentation outputId before JavaScript in NodeJS constructs the complete merge request.

Build the ordered merge payload

var mergeData = new FormData();
        mergeData.append("id", imagePDFID);
        mergeData.append("pages[]", "1-last");
        mergeData.append("type[]", "id");
        mergeData.append("id", pptPDFID);
        mergeData.append("pages[]", "1-last");
        mergeData.append("type[]", "id");
        mergeData.append("output", "pdfrest_merged_pdf");

        var mergeConfig = {
          method: "post",
          maxBodyLength: Infinity,
          url: apiUrl + "/merged-pdf",
          headers: {
            "Api-Key": apiKey,
            ...mergeData.getHeaders(),
          },
          data: mergeData,
        };

The JavaScript in NodeJS merge body groups each resource ID with its input type and selected pages. Their repeated-field order controls how the converted sources appear in the Merge Different Formats Together as a PDF result returned to JavaScript in NodeJS.

Read the final merge response

axios(mergeConfig)
          .then(function (response) {
            console.log(JSON.stringify(response.data)); // If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample
          })
          .catch(function (error) {
            console.log(error);
          });

The final Merge Different Formats Together as a PDF handling in JavaScript in NodeJS exposes the HTTP result and JSON body. Before using a Merge Different Formats Together as a PDF 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 have followed the complete JavaScript in NodeJS sequence from source conversion through resource-ID handoff and final PDF assembly.

Handle failure independently at each stage and record which source produced each ID. Intermediate resources are temporary, so complete the merge and retain the final result within the configured file-retention period.

Try the Merge Different Formats Together as a PDF workflow with a representative file in API Lab, then adapt the request in JavaScript in NodeJS. The Merge PDFs API Tool documentation provides the complete JavaScript in NodeJS context for Merge Different Formats Together as a PDF values, defaults, and limitations.

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