PDF to Image Conversion Utility
pdf2pic is a robust Node.js utility library designed for converting PDF documents into various image formats (like PNG, JPEG), base64 encoded strings, or raw image buffers. The current stable version is 3.2.0, with the project maintaining an active release cadence, frequently delivering patches and minor updates. A key differentiator of pdf2pic is its flexibility in output types and its ability to handle conversions from file paths, buffers, or base64 input. It acts as a wrapper around powerful external system dependencies: GraphicsMagick (or ImageMagick) for image processing and Ghostscript for PDF rendering. This design necessitates prior installation of these tools on the host system. The library ships with comprehensive TypeScript type definitions, enhancing the development experience for TypeScript users, and requires Node.js version 14 or higher.
Common errors
-
Error: spawn gm ENOENT
cause The GraphicsMagick or ImageMagick system executable is not found. It's either not installed or not configured correctly in the system's PATH.fixInstall GraphicsMagick or ImageMagick on your operating system (e.g., `sudo apt-get install graphicsmagick` on Debian/Ubuntu, `brew install graphicsmagick` on macOS). Verify its presence by running `gm -version` or `convert -version` in your terminal. -
Error: spawn gs ENOENT
cause The Ghostscript system executable is not found. It's either not installed or not configured correctly in the system's PATH, which is crucial for PDF rendering.fixInstall Ghostscript on your operating system (e.g., `sudo apt-get install ghostscript` on Debian/Ubuntu, `brew install ghostscript` on macOS). Verify its presence by running `gs -version` in your terminal. -
Error: Command failed: gm convert: No such file or directory
cause This error typically indicates that the PDF file path provided to `fromPath` is incorrect, the file does not exist at that location, or the file is not a valid PDF that GraphicsMagick can process.fixEnsure the `filePath` argument points to a valid, accessible PDF file. Use an absolute path or carefully resolve relative paths. Check file permissions. -
TypeError: (0 , pdf2pic__WEBPACK_IMPORTED_MODULE_0__.fromPath) is not a function
cause This Webpack or bundler error (or similar 'is not a function' errors) usually means an incorrect import style, attempting to use named exports as a default import, or misconfiguring module resolution.fixAlways use named imports: `import { fromPath } from 'pdf2pic';`. If using CommonJS, use destructuring: `const { fromPath } = require('pdf2pic');`.
Warnings
- breaking Node.js 16 support was temporarily dropped in version 3.1.2, potentially causing issues for users on that Node.js version. It was re-added in version 3.1.3.
- gotcha pdf2pic relies heavily on external system dependencies: GraphicsMagick (or ImageMagick) and Ghostscript. These must be installed on the host system and be accessible in the system's PATH environment variable for the library to function correctly.
- gotcha Older versions of pdf2pic (prior to 3.1.4) used an underlying `gm` dependency that contained a `cross-spawn` vulnerability. Upgrading is recommended for security.
- deprecated The `fs-extra` dependency was removed in version 3.0.1. While not directly breaking for standard use, any implicit reliance on `fs-extra` functionalities through `pdf2pic` in older versions might be affected.
Install
-
npm install pdf2pic -
yarn add pdf2pic -
pnpm add pdf2pic
Imports
- fromPath
const fromPath = require('pdf2pic').fromPath;import { fromPath } from 'pdf2pic'; - fromBuffer
import pdf2pic from 'pdf2pic'; // pdf2pic.fromBuffer
import { fromBuffer } from 'pdf2pic'; - Pdf2picOptions
import { Pdf2picOptions } from 'pdf2pic';import type { Pdf2picOptions } from 'pdf2pic';
Quickstart
import { fromPath } from "pdf2pic";
import path from "path";
import { promises as fs } from 'fs';
// Ensure the output directory exists
const savePath = path.resolve("./images");
await fs.mkdir(savePath, { recursive: true });
// In a real application, provide a full, valid path to your PDF.
// For this example, ensure 'sample.pdf' exists in your project root.
const pdfFilePath = path.resolve("./sample.pdf");
const options = {
density: 100,
saveFilename: "converted_page",
savePath: savePath,
format: "png",
width: 600,
height: 600
};
const convert = fromPath(pdfFilePath, options);
const pageToConvertAsImage = 1;
try {
const result = await convert(pageToConvertAsImage, { responseType: "image" });
console.log(`Page ${pageToConvertAsImage} converted successfully.`);
console.log(`Output: ${path.join(result.path, result.name)}`);
} catch (error) {
console.error("Error converting PDF page:", error.message);
// Provide detailed error messages for common prerequisites issues
if (error.message.includes("gm ENOENT")) {
console.error("GraphicsMagick/ImageMagick not found. Ensure it's installed and in PATH.");
console.error("See: https://github.com/yakovmeister/pdf2image#prerequisites");
} else if (error.message.includes("gs ENOENT")) {
console.error("Ghostscript not found. Ensure it's installed and in PATH.");
console.error("See: https://github.com/yakovmeister/pdf2image#prerequisites");
}
}
// Optional: Example for converting all pages
try {
console.log("\nAttempting to convert all pages...");
// To run this, you must have a 'sample.pdf' in your project root.
// For testing, consider using a small dummy PDF.
const bulkResult = await fromPath(pdfFilePath, options).bulk(-1, { responseType: "image" });
console.log(`Successfully converted ${bulkResult.length} pages.`);
} catch (error) {
console.error("Error converting all PDF pages:", error.message);
}