Images To PDF

To convert a single image to a PDF document, simply input the file path into the PdfGenerator.imageToPdf method and export the resulting PDF document.

Converting multiple images to a PDF involves using an array of file paths. Below is the complete guide with a properly formatted code snippet.

const fs = require('fs');
const path = require('path');
const PdfGenerator = require('iron-pdf');

// Directory containing image files
const imageDirectoryPath = './images';

// Use fs.readdir to read all files from the image directory
fs.readdir(imageDirectoryPath, (err, files) => {
    if (err) throw err;

    // Filter the image files to include only .jpg and .jpeg extensions
    const jpegFiles = files.filter(file => {
        return path.extname(file).toLowerCase() === '.jpg' || path.extname(file).toLowerCase() === '.jpeg';
    });

    // Map the filtered file names to their full paths
    const filePaths = jpegFiles.map(file => path.join(imageDirectoryPath, file));

    // Convert the images to a PDF using PdfGenerator's imageToPdf method
    PdfGenerator.imageToPdf({ input: filePaths })
        .then(result => {
            // Save the resulting PDF document
            return result.saveAs('composite.pdf');
        })
        .then(() => {
            console.log('PDF successfully created and saved as "composite.pdf".');
        })
        .catch(error => {
            console.error('Error during PDF generation: ', error);
        });
});

Code Explanation

  1. Import Required Modules:

    • fs: A core Node.js module for interacting with the file system.
    • path: A core module for handling and transforming file paths.
    • PdfGenerator: A module from the IronPDF library used for generating PDFs.
  2. Read Directory:

    • fs.readdir: Reads the directory specified by imageDirectoryPath.
    • Filters and returns files that have .jpg or .jpeg extensions.
  3. Build Full File Paths:

    • Uses path.join to construct the full paths of filtered image files.
  4. Convert Images to PDF:

    • The PdfGenerator.imageToPdf method takes the array of image paths and converts them to a single PDF.
  5. Save the PDF:
    • The saveAs method saves the generated PDF as composite.pdf.

For more details on converting images to PDFs using IronPDF, visit the IronPDF product page.