How to convert images to PDF in Node.js
In this tutorial, you’ll learn the process of converting an image to a PDF using Node.js. In the first part, you’ll use the pdf-lib library, and in the second part, you’ll use Nutrient Node.js SDK to convert an image to a PDF.
Prerequisites
Before you begin, make sure you have the following installed:
-
Node.js — You can download it from the official Node.js website.
-
npm — Node Package Manager comes bundled with Node.js, so it’ll be installed by default.
Step 1 — Setting up your project
-
Create a new directory for your project:
mkdir image-to-pdf-converter cd image-to-pdf-converter
-
Initialize a new Node.js project:
npm init -y
-
Install the pdf-lib library:
npm install pdf-lib
Step 2 — Writing the conversion code
-
Create a file named
convert.js
in your project directory and add the following code:
const fs = require('fs'); const { PDFDocument, rgb } = 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. const imageEmbed = 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, color: rgb(0, 0, 0), // Set the image color to black. }); // 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); });
-
Replace
'input.jpg'
with the path to the image you want to convert and'output.pdf'
with the desired path for the output PDF. -
Run the conversion script using the following command:
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
Nutrient Node.js SDK introduces a suite of capabilities for document conversion within Node.js applications. It empowers developers to seamlessly convert Word, Excel, PowerPoint, and image files into PDFs, all without the need for MS Office or third-party open source dependencies. Furthermore, Nutrient Node.js SDK offers a convenient way to integrate advanced PDF functionality into any Node.js application.
Key features of Nutrient Node.js SDK
Nutrient Node.js SDK comes with an array of features that make it an excellent choice for document conversion within Node.js applications:
-
Versatile conversion — Nutrient Node.js SDK supports converting a wide range of file formats, including PDF, Word, Excel, PowerPoint, TIFF, JPG, and PNG. This diverse format support enables seamless document conversion without third-party tools.
-
Custom font support — The library intelligently handles custom fonts during conversion, ensuring that documents maintain their visual integrity and consistency, even when converted across formats.
-
Diverse file support — Nutrient Node.js SDK supports handling various formats beyond images, such as DOCX, XLSX, PPTX, and other popular document formats, making it a comprehensive solution for document conversion.
-
Advanced rendering — The library offers advanced rendering capabilities, allowing you to render PDF pages into formats like PNG or WebP. This provides flexibility in choosing how to visualize the converted documents.
Comparison with pdf-lib
When comparing Nutrient Node.js SDK with the pdf-lib library, consider the following:
-
Conversion scope — Nutrient Node.js SDK boasts a broader scope of supported formats, encompassing PDF and various Office formats like Word, Excel, and PowerPoint. In contrast, pdf-lib primarily focuses on PDF creation and manipulation, with image embedding as a specific use case.
-
Font handling — Nutrient Node.js SDK excels in its intelligent custom font handling during conversion, ensuring consistent visual representation across different formats.
-
Advanced rendering — Nutrient Node.js SDK provides advanced rendering options, allowing you to render PDF pages into different image formats, a capability that caters to diverse visualization needs.
Integrating Nutrient Node.js SDK
-
Initialize a new Node.js project:
npm init -y
This command creates a package.json
file in your project directory, which is essential for managing your project’s dependencies.
-
Install the Nutrient Node.js SDK package:
npm install @pspdfkit/nodejs
-
Place your image document (e.g. image.png) in your project directory.
-
Create a new JavaScript file named
index.js
in your project directory. This script will take care of the conversion process for you.
const { load } = require('@pspdfkit/nodejs'); 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 loads an image and exports it to a PDF. It initiates by reading the image data and proceeds to convert it into a PDF format. The resulting PDF, named converted.pdf
, is then saved within your project directory.
Supported Image Formats | |
---|---|
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 akey
andappName
when calling theload()
function. For details on obtaining a trial license key, please get in touch with Sales.
-
Execute the script in your terminal to initiate the conversion process:
node index.js
Conclusion
In this post, you explored two approaches to document conversion in Node.js applications. The first part covered using the pdf-lib library to convert an image to PDF. In the second part, you learned about Nutrient Node.js SDK, a robust SDK offering versatile document conversion features.
To get started with Nutrient Node.js SDK, you can either:
-
Start your free trial to test the library and see how it works in your application.
-
Launch our demo to see the viewer in action.
FAQ
Here are a few frequently asked questions about image-to-PDF conversion in Node.js.
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.