CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pdf2pic

A utility for converting pdf to image formats with support for different outputs: directly to file, base64 or buffer.

Overall
score

97%

Overview
Eval results
Files

conversion.mddocs/

PDF Conversion

The Convert interface provides both single-page and bulk conversion capabilities with three output formats: image files, base64 strings, and buffers.

Capabilities

Single Page Conversion

Convert individual PDF pages with different output formats based on the responseType option.

/**
 * Convert a specific PDF page (defaults to page 1, image output)
 * @param pages - Page number to convert (1-indexed), defaults to 1
 * @returns Promise resolving to WriteImageResponse
 */
(pages?: number): Promise<WriteImageResponse>;

/**
 * Convert a specific PDF page to image file
 * @param pages - Page number to convert (1-indexed)
 * @param options - Conversion options with responseType
 * @returns Promise resolving to WriteImageResponse
 */
(pages: number, options: { responseType?: undefined }): Promise<WriteImageResponse>;
(pages: number, options: { responseType: 'image' }): Promise<WriteImageResponse>;

/**
 * Convert a specific PDF page to base64 string
 * @param pages - Page number to convert (1-indexed)
 * @param options - Conversion options with responseType set to 'base64'
 * @returns Promise resolving to ToBase64Response
 */
(pages: number, options: { responseType: 'base64' }): Promise<ToBase64Response>;

/**
 * Convert a specific PDF page to buffer
 * @param pages - Page number to convert (1-indexed)
 * @param options - Conversion options with responseType set to 'buffer'
 * @returns Promise resolving to BufferResponse
 */
(pages: number, options: { responseType: 'buffer' }): Promise<BufferResponse>;

Usage Examples:

import { fromPath } from "pdf2pic";

const convert = fromPath("/path/to/document.pdf", {
  format: "jpg",
  quality: 90,
  width: 1200,
  height: 800
});

// Convert page 1 to image file (default behavior)
const imageResult = await convert(1);
console.log(`Saved to: ${imageResult.path}`);
console.log(`File size: ${imageResult.fileSize} KB`);

// Convert page 2 to base64
const base64Result = await convert(2, { responseType: "base64" });
console.log(`Base64 length: ${base64Result.base64.length}`);
console.log(`Image size: ${base64Result.size}`);

// Convert page 3 to buffer for processing
const bufferResult = await convert(3, { responseType: "buffer" });
const imageBuffer = bufferResult.buffer;
console.log(`Buffer size: ${imageBuffer.length} bytes`);

Bulk Conversion

Convert multiple PDF pages in a single operation with automatic batching for performance optimization.

interface BulkConvert {
  /**
   * Convert multiple pages to image files (default behavior)
   * @param pages - Page numbers to convert, or -1 for all pages
   * @returns Promise resolving to array of WriteImageResponse
   */
  (pages?: number | number[]): Promise<WriteImageResponse[]>;
  (pages: number | number[], options: { responseType?: undefined }): Promise<WriteImageResponse[]>;
  (pages: number | number[], options: { responseType: 'image' }): Promise<WriteImageResponse[]>;

  /**
   * Convert multiple pages to base64 strings
   * @param pages - Page numbers to convert, or -1 for all pages
   * @param options - Conversion options with responseType set to 'base64'
   * @returns Promise resolving to array of ToBase64Response
   */
  (pages: number | number[], options: { responseType: 'base64' }): Promise<ToBase64Response[]>;

  /**
   * Convert multiple pages to buffers
   * @param pages - Page numbers to convert, or -1 for all pages
   * @param options - Conversion options with responseType set to 'buffer'
   * @returns Promise resolving to array of BufferResponse
   */
  (pages: number | number[], options: { responseType: 'buffer' }): Promise<BufferResponse[]>;
}

Usage Examples:

import { fromBuffer } from "pdf2pic";

const convert = fromBuffer(pdfBuffer, {
  format: "png",
  width: 800,
  savePath: "./output"
});

// Convert specific pages to image files
const specificPages = await convert.bulk([1, 3, 5], { responseType: "image" });
specificPages.forEach(result => {
  console.log(`Page ${result.page}: ${result.name} (${result.fileSize} KB)`);
});

// Convert all pages to base64 (-1 means all pages)
const allPagesBase64 = await convert.bulk(-1, { responseType: "base64" });
console.log(`Converted ${allPagesBase64.length} pages to base64`);

// Convert range of pages to buffers
const pageRange = [1, 2, 3, 4, 5];
const bufferResults = await convert.bulk(pageRange, { responseType: "buffer" });
bufferResults.forEach((result, index) => {
  console.log(`Page ${result.page} buffer: ${result.buffer.length} bytes`);
});

// Convert first 10 pages (or all if PDF has fewer)
const firstTenPages = Array.from({ length: 10 }, (_, i) => i + 1);
const results = await convert.bulk(firstTenPages);

Configuration Methods

Methods for modifying conversion settings after initialization.

/**
 * Apply current options to the GraphicsMagick instance
 * Call this after modifying any settings to ensure they take effect
 */
setOptions(): void;

/**
 * Configure the GraphicsMagick backend
 * @param gmClass - GraphicsMagick class configuration
 *   - boolean: true for ImageMagick, false for GraphicsMagick
 *   - string: custom path to graphics processing binary
 */
setGMClass(gmClass: string | boolean): void;

Usage Examples:

import { fromPath } from "pdf2pic";

const convert = fromPath("/path/to/document.pdf");

// Switch to ImageMagick backend
convert.setGMClass(true);
convert.setOptions(); // Apply the change

// Or specify custom binary path
convert.setGMClass("/usr/local/bin/gm");
convert.setOptions();

// Convert with new settings
const result = await convert(1);

Response Format Details

WriteImageResponse

Returned when converting to image files (responseType: 'image' or default).

interface WriteImageResponse {
  name?: string;        // Generated filename (e.g., "page.1.png")
  fileSize?: number;    // File size in kilobytes
  path?: string;        // Full path to saved image file
  size?: string;        // Image dimensions (e.g., "800x600")
  page?: number;        // Page number that was converted
}

ToBase64Response

Returned when converting to base64 strings (responseType: 'base64').

interface ToBase64Response {
  base64?: string;      // Base64-encoded image data
  size?: string;        // Image dimensions (e.g., "800x600")
  page?: number;        // Page number that was converted
}

BufferResponse

Returned when converting to buffers (responseType: 'buffer').

interface BufferResponse {
  buffer?: Buffer;      // Raw image data as Node.js Buffer
  size?: string;        // Image dimensions (e.g., "800x600")
  page?: number;        // Page number that was converted
}

Performance Considerations

Bulk Conversion Batching

The bulk conversion method automatically processes pages in batches of 10 to optimize memory usage and prevent system overload:

// Internally batches large requests
const manyPages = Array.from({ length: 100 }, (_, i) => i + 1);
const results = await convert.bulk(manyPages); // Processed in 10 batches of 10 pages each

Memory Management

  • Image Files: Most memory-efficient for large batches
  • Base64: Moderate memory usage, good for web APIs
  • Buffers: Highest memory usage, keep in memory only as needed

Error Handling

import { fromPath } from "pdf2pic";

const convert = fromPath("/path/to/document.pdf");

try {
  // This will throw if page number is invalid
  const result = await convert(0); // Pages are 1-indexed
} catch (error) {
  if (error.message.includes("Page number should be more than or equal 1")) {
    console.error("Invalid page number provided");
  }
}

try {
  // This will handle pages that don't exist gracefully
  const results = await convert.bulk([1, 2, 999]); // Page 999 may not exist
  console.log(`Successfully converted ${results.length} pages`);
} catch (error) {
  console.error("Bulk conversion failed:", error.message);
}

Install with Tessl CLI

npx tessl i tessl/npm-pdf2pic

docs

configuration.md

conversion.md

index.md

input-sources.md

tile.json