How to Merge PDF in Node.js

Merge or combine two PDF into single PDF in Node.js

Combining and merging files is a very popular task during work with a large number of documents. Sometimes, when working with documents and images, when they are scanned, processed, and organized, several files are created. But what if you need to store everything in one file? Or do you not want to print several documents? Concatenate two PDF files with Aspose.PDF for Node.js via C++.

In case you want to merge two PDFs, you can use AsposePdfMerge2Files function. Please check the following code snippet in order to merge two PDFs files in Node.js environment.

CommonJS:

  1. Call require and import asposepdfnodejs module as AsposePdf variable.
  2. Specify the name of the PDF files which will be merged.
  3. Call AsposePdf as Promise and perform the operation for merging. Receive the object if successful.
  4. Call the function AsposePdfMerge2Files.
  5. Merge two PDF files. Thus, if ‘json.errorCode’ is 0, the result of the operation is saved in “ResultMerge.pdf”. If the json.errorCode parameter is not 0 and, accordingly, an error appears in your file, the error information will be contained in ‘json.errorText’.

  const AsposePdf = require('asposepdfnodejs');
  const pdf_file = 'Aspose.pdf';
  AsposePdf().then(AsposePdfModule => {
      /*Merge two PDF-files and save the "ResultMerge.pdf"*/
      const json = AsposePdfModule.AsposePdfMerge2Files(pdf_file, pdf_file, "ResultMerge.pdf");
      console.log("AsposePdfMerge2Files => %O", json.errorCode == 0 ? json.fileNameResult : json.errorText);
  });

ECMAScript/ES6:

  1. Import the asposepdfnodejs module.
  2. Specify the name of the PDF files which will be merged.
  3. Initialize the AsposePdf module. Receive the object if successful.
  4. Call the function AsposePdfMerge2Files.
  5. Merge two PDF files. Thus, if ‘json.errorCode’ is 0, the result of the operation is saved in “ResultMerge.pdf”. If the json.errorCode parameter is not 0 and, accordingly, an error appears in your file, the error information will be contained in ‘json.errorText’.

  import AsposePdf from 'asposepdfnodejs';
  const AsposePdfModule = await AsposePdf();
  const pdf_file = 'Aspose.pdf';
  /*Merge two PDF-files and save the "ResultMerge.pdf"*/
  const json = AsposePdfModule.AsposePdfMerge2Files(pdf_file, pdf_file, "ResultMerge.pdf");
  console.log("AsposePdfMerge2Files => %O", json.errorCode == 0 ? json.fileNameResult : json.errorText);