Convert Multiple images to PDF in Node.js

This tutorial will guide you through the process of using PDFKit to Convert Multiple images to PDF in Node.js. Converting multiple images to a single PDF file is a common requirement in both web and automation projects. In a Node.js environment, this can be easily achieved using the popular NPM package, PDFKit.  By the end, you will have learned how to install the package, run a basic conversion example, handle potential errors, and explore advanced features for customizing your PDF output.Convert Multiple images to PDF in Node.js

Table of Contents

Getting Started

Before diving into the code examples, ensure that you have Node.js installed on your system. You can download the latest version from the Node.js official website if it’s not installed already.

Installing PDFKit

To get started, you need to install the PDFKit library. Open your terminal or command prompt and navigate to the root directory of your Node.js project. Run the following command:

npm install pdfkit

Basic Conversion Example

Let’s begin with a basic example of converting multiple images to a PDF. For this, you need to have a set of images ready in your project directory.

// Require the PDFKit library
const PDFDocument = require('pdfkit');
const fs = require('fs');

// Create a new PDF document
const doc = new PDFDocument();

// Pipe the PDF into a writable stream
doc.pipe(fs.createWriteStream('output.pdf'));

// Define an array with paths to your images
const imagePaths = ['image1.jpg', 'image2.jpg', 'image3.png'];

// Add each image to the PDF
imagePaths.forEach(path => {
  doc.addPage().image(path, {
    fit: [250, 300],
    align: 'center',
    valign: 'center'
  });
});

// Finalize the PDF and end the document
doc.end();

Advanced Usage

PDFKit also offers advanced features that allow you to set image quality, add text, change page dimensions, and much more. Here’s an example:

// Advanced example with custom page sizes and additional text
const doc = new PDFDocument({ size: 'A4' });

// ...setup and document creation code as above...

imagePaths.forEach((path, index) => {
  doc.addPage().image(path, 0, 0, { width: 595.28, height: 841.89 });
  // Add image captions
  doc.fontSize(12).text(`Image ${index + 1}`, 200, 800);
});

// ...finalize document as above...

Error Handling

Error handling is crucial when working with files and streams. Here’s how you can manage errors with the ‘finish’ and ‘error’ events when writing to a stream:

const writeStream = fs.createWriteStream('output.pdf');

writeStream.on('finish', () => {
  console.log('PDF file written successfully');
});

writeStream.on('error', (err) => {
  console.error('An error occurred', err);
});

doc.pipe(writeStream);
doc.end();

Conclusion

In this tutorial, you’ve learned how to Convert Multiple images to PDF in Node.js using the PDFKit library. You started with a simple example to understand the basics and then advanced to custom PDF creation with more control over the layout and content. Remember to implement proper error handling in your applications to ensure a smooth user experience.

References