How to convert images to PDF in Node.js

Table of contents

    How to convert images to PDF in Node.js
    Summary
    • pdf-lib — Free, good for simple image-to-PDF conversion (JPEG and PNG)
    • Nutrient Node.js SDK — One SDK for images, Office docs, and PDFs. Start with image conversion. Then handle Word, Excel, and PowerPoint without adding dependencies.

    In this tutorial, you’ll learn how to convert an image to a PDF using Node.js. In the first part, you’ll use the pdf-lib(opens in a new tab) library, and in the second part, you’ll use Nutrient Node.js SDK.

    Prerequisites

    Before you begin, make sure you have the following installed:

    Step 1 — Setting up your project

    1. Create a new directory for your project:

      Terminal window
      mkdir image-to-pdf-converter
      cd image-to-pdf-converter
    2. Initialize a new Node.js project:

      Terminal window
      npm init -y
    3. Install the pdf-lib library:

      Terminal window
      npm install pdf-lib

    Step 2 — Writing the conversion code

    1. Create a file named convert.js in your project directory and add the following code:

      const fs = require("fs");
      const { PDFDocument } = require("pdf-lib");
      async function convertImageToPdf(imagePath, pdfPath) {
      // Read the image file asynchronously.
      const image = await fs.promises.readFile(imagePath);
      // Create a new PDF document.
      const pdfDoc = await PDFDocument.create();
      // Add a new page to the PDF document with a dimension of 400×400 points.
      const page = pdfDoc.addPage([400, 400]);
      // Embed the image into the PDF document.
      // Use embedPng() for PNG files, embedJpg() for JPEG files.
      const imageEmbed = imagePath.toLowerCase().endsWith(".png")
      ? await pdfDoc.embedPng(image)
      : await pdfDoc.embedJpg(image);
      // Scale the image to fit within the page dimensions while preserving aspect ratio.
      const { width, height } = imageEmbed.scaleToFit(
      page.getWidth(),
      page.getHeight(),
      );
      // Draw the image on the PDF page.
      page.drawImage(imageEmbed, {
      x: page.getWidth() / 2 - width / 2, // Center the image horizontally.
      y: page.getHeight() / 2 - height / 2, // Center the image vertically.
      width,
      height,
      });
      // Save the PDF document as bytes.
      const pdfBytes = await pdfDoc.save();
      // Write the PDF bytes to a file asynchronously.
      await fs.promises.writeFile(pdfPath, pdfBytes);
      }
      // Call the conversion function with input and output file paths.
      convertImageToPdf("input.jpg", "output.pdf")
      .then(() => {
      console.log("Image converted to PDF successfully!");
      })
      .catch((error) => {
      console.error("Error converting image to PDF:", error);
      });
    2. Replace 'input.jpg' with the path to the image you want to convert (JPEG or PNG) and 'output.pdf' with the desired path for the output PDF.

    3. Run the conversion script using the following command:

      Terminal window
      node convert.js

    Check your project directory for the generated output.pdf file.

    You’ve successfully converted an image to a PDF using Node.js and the pdf-lib library.

    Nutrient Node.js SDK

    If you need more than basic image-to-PDF conversion, Nutrient Node.js SDK gives you a single dependency for all your document processing needs. Instead of juggling multiple libraries for different file types, you get one SDK that handles images, Office documents, and PDFs — with no MS Office installation required.

    Why use Nutrient for image conversion?

    • One SDK, multiple formats — Convert images today. Then use the same SDK to handle Word, Excel, and PowerPoint files tomorrow. No need to add new dependencies as your requirements grow.
    • Production-ready output — Custom fonts are preserved automatically, so your converted PDFs look exactly as intended without extra configuration.
    • Two-way conversion — Convert images to PDF, or render PDF pages back to PNG/WebP. Handle both directions with the same tool.
    • No external dependencies — Skip installing MS Office, LibreOffice, or other converters on your server. Nutrient runs standalone.

    When to choose Nutrient over pdf-lib

    ScenarioNutrient Node.js SDKpdf-lib
    Image-to-PDF onlyWorks, but may be more than you needGood fit for simple use cases
    Multiple file typesSingle SDK handles images, Office docs, and PDFsRequires additional libraries
    Font fidelity mattersAutomatic font preservationManual font handling required
    Need PDF-to-imageBuilt-in PNG/WebP exportNot supported

    Integrating Nutrient Node.js SDK

    1. Initialize a new Node.js project:

      Terminal window
      npm init -y

      This command creates a package.json file in your project directory, which is essential for managing your project’s dependencies.

    2. Install the Nutrient Node.js SDK package:

      Terminal window
      npm install @nutrient-sdk/node
    3. Place your image document (e.g. image.png) in your project directory.

    4. Create a new JavaScript file named index.js in your project directory. This script handles the conversion.

      const { load } = require("@nutrient-sdk/node");
      const fs = require("fs");
      (async () => {
      const pngImage = fs.readFileSync("image.png");
      const instance = await load({ document: pngImage });
      const buffer = await instance.exportPDF();
      fs.writeFileSync("converted.pdf", Buffer.from(buffer));
      instance.close();
      })();

      This example reads the image file, converts it to PDF, and saves the result as converted.pdf in your project directory.

      FormatSupported
      PNG
      JPEG, JPG
      TIFF, TIF

      By default, the resulting PDF will include a Nutrient watermark. To exclude the watermark, you can specify the license property with a key and appName when calling the load() function. For details on obtaining a trial license key, please get in touch with Sales.

    5. Execute the script in your terminal to initiate the conversion process:

      Terminal window
      node index.js

    Conclusion

    In this post, you learned two ways to convert images to PDF in Node.js. pdf-lib works well for straightforward image embedding. But if your project will eventually need Office document conversion, PDF rendering, or other document operations, Nutrient Node.js SDK lets you start with image conversion and scale to handle everything else — without adding more dependencies later.

    To get started with Nutrient Node.js SDK:

    FAQ

    How can I convert an image to PDF using Node.js?

    You can convert an image to PDF using Node.js with the pdf-lib library by creating a new PDF document, embedding the image, and saving the file.

    What are the best Node.js libraries for image-to-PDF conversion?

    The top libraries for converting images to PDFs in Node.js include pdf-lib and Nutrient Node.js SDK, each offering different features for PDF creation and manipulation.

    How do I convert an image to a PDF using Nutrient Node.js SDK?

    To convert an image to a PDF with Nutrient Node.js SDK, load the image file into the SDK. Then use its PDF export functionality to generate the PDF.

    What file formats are supported by Nutrient Node.js SDK?

    Nutrient Node.js SDK supports a range of file formats, including PDF, Word, Excel, PowerPoint, TIFF, JPG, and PNG, enabling comprehensive document conversion.

    How does Nutrient Node.js SDK compare to other PDF libraries?

    Nutrient Node.js SDK offers broader format support and advanced rendering capabilities compared to other libraries like pdf-lib, which primarily focus on PDF creation and manipulation.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Try for free Ready to get started?