pdf-img-convert

repository·master·Indexed 41 days ago

https://github.com/ol-th/pdf-img-convert.js

A lightweight JavaScript library built on Mozilla's PDF.js that converts PDF documents into images (PNG, JPEG, or WebP) without relying on the filesystem or external binaries. Version 2.0.0 provides the asynchronous convert() function, which supports PDF URLs, local paths, Buffers, Uint8Arrays, and Base64 data, returning an array of image buffers or Base64 strings based on the conversion_config.

Tokens
1.6K
Snippets
6
Records
7
Agent score
19%

What's inside pdf-img-convert

  1. Configure conversion options

    master

    You can pass an optional conversion_config object as the second argument to convert() to customize the output.

    Configuration Keys:

    • width (Number): Target width in pixels. If both width and height are provided, width takes precedence.
    • height (Number): Target height in pixels.
    • scale (Number): Viewport scale ratio. Defaults to 1.
    • page_numbers (Array<number>): A 1-indexed list of specific pages to render (e.g., [1, 3]).
    • base64 (Boolean): If true, the function returns an array of base64-encoded strings instead of Uint8Array objects.
    const config = {
      width: 100,
      height: 100,
      scale: 2,
      page_numbers: [1, 2, 3],
      base64: true
    };
    
    const output = await pdf2img.convert('./example.pdf', config);
  2. Configure output dimensions and scale

    master

    You can control the resolution of the output images using scale, width, or height in the conversion_config object. The logic follows this priority:

    1. Width/Height: If width or height is provided, the function calculates a scale factor to match that specific dimension.
    2. Scale: If neither width nor height is provided, the scale multiplier is applied to the original viewport.

    Note: If width or height are provided as values <= 0, the library logs an error and defaults to 100% scale.

  3. Convert PDF to Base64 strings

    master

    To receive base64-encoded strings instead of raw binary data, set the base64 key to true in the configuration object. This is useful for web applications that need to display images directly in the browser or send them via JSON APIs.

    import pdf2img from 'pdf-img-convert';
    
    let config = {
        base64: true,
        scale: 2
    };
    
    async function processPDF() {
        const pdf2img = await import("pdf-img-convert");
        const output = await pdf2img.convert('./examples/example.pdf', config);
        
        // output is an array of base64 strings
        output.forEach((base64Data, index) => {
            console.log(`Page ${index + 1} base64:`, base64Data);
        });
    }
    
    processPDF();
  4. Use the convert() function

    master

    The core API is the asynchronous convert function. It accepts several input formats and returns a Promise that resolves to an Array of images.

    Supported Input Formats:

    • URL of a PDF (e.g., https://example.com/sample.pdf)
    • Path to a local PDF file (e.g., ./sample.pdf)
    • A Buffer object containing PDF data
    • A Uint8Array object containing PDF data
    • Base64-encoded PDF data

    Default Output: By default, the function returns an Array of Uint8Array objects, where each object represents a PNG image.

    import pdf2img from 'pdf-img-convert';
    
    // Example: converting a local file
    const pdfArray = await pdf2img.convert('./sample.pdf');
    // pdfArray is an Array of Uint8Array (PNG data)
  5. Convert PDF to images using convert()

    master

    The convert function is the primary API for transforming PDF data into an array of images. It supports various input formats and allows for detailed configuration of the output.

    Input Types

    The pdf parameter can be one of the following:

    • URL: A string representing a remote PDF URL (fetched via node-fetch).
    • Base64 String: A string following the Data URI pattern: pdfData:pdf/[type];base64,[data].
    • File Path: A string representing a local file path.
    • Buffer: A Node.js Buffer object.
    • Uint8Array: A raw byte array of the PDF data.

    Configuration Options

    The conversion_config object allows you to customize the output:

    • page_numbers: An array of specific page numbers to convert (e.g., [1, 3]). If omitted, all pages are converted.
    • scale: A numeric multiplier for the output size (default is 1.0).
    • width: Target width in pixels. If provided, the scale is adjusted to match this width.
    • height: Target height in pixels. If provided, the scale is adjusted to match this height.
    • format: The output image format. Supported values are 'jpeg', 'webp', or 'png' (default).
    • base64: A boolean. If true, the returned array contains Base64 encoded strings instead of Uint8Array buffers.
    import { convert } from 'pdf-img-convert';
    
    // Example: Convert specific pages to JPEG base64 strings
    const images = await convert('path/to/file.pdf', {
      page_numbers: [1, 2],
      format: 'jpeg',
      base64: true,
      scale: 2.0
    });
    
    // images is an array of base64 strings
  6. Reference: conversion_config options

    master

    The following keys are available in the conversion_config object passed to convert():

    {
      page_numbers?: number[]; // Array of page indices (1-based)
      scale?: number;          // Multiplier for viewport
      width?: number;          // Target width in pixels
      height?: number;         // Target height in pixels
      format?: 'jpeg' | 'webp' | 'png'; // Image format
      base64?: boolean;        // Return base64 strings instead of Uint8Array
    }