pdf2pic Documentation

repository·master·Indexed 19 days ago

https://github.com/yakovmeister/pdf2image

A Node.js utility for converting PDF files into image formats, base64 strings, or buffers. It acts as a wrapper around GraphicsMagick and Ghostscript, providing entry points via fromPath, fromBuffer, and fromBase64 for both single-page and bulk conversions.

Tokens
4.9K
Snippets
17
Records
22
Agent score
67%

What's inside pdf2pic

  1. Install GraphicsMagick and Ghostscript on AWS Lambda

    master

    To use these libraries in AWS Lambda, you must add them via Lambda Layers. You can use community-driven prebuilt layers or build your own.

    Example ARNs for reference:

    • GraphicsMagick: arn:aws:lambda:us-east-1:175033217214:layer:graphicsmagick:2
    • Ghostscript: arn:aws:lambda:us-east-1:764866452798:layer:ghostscript:15
    arn:aws:lambda:us-east-1:175033217214:layer:graphicsmagick:2
    arn:aws:lambda:us-east-1:764866452798:layer:ghostscript:15
  2. Install GraphicsMagick and Ghostscript on Windows

    master

    Windows users must download the installers manually and add the executable directories to the system PATH environment variable.

    1. Download Ghostscript: Use version 9.52 (versions 9.53 or later may cause errors). Download link.
    2. Download GraphicsMagick: Download link.
    3. Configure PATH: Add the following directory patterns to your PATH environment variable:
      • C:\Program Files\gs\gs****\bin
      • C:\Program Files\GraphicsMagick-****
  3. Build and run the pdf2pic Docker example

    master

    This example provides a Dockerfile based on Alpine Linux to demonstrate how to run pdf2pic in a containerized environment.

    To use this example, build the image using the provided tag and then run the container.

    # Build the image
    docker build -t pdf2pic-docker .
    
    # Run the container
    docker run pdf2pic-docker
  4. Migrate responseType from boolean to object in v3.x

    master

    In pdf2pic v3.x, the boolean parameter used to request a specific response format (like base64) has been deprecated. You must now pass an options object with the responseType key instead. This change applies to the convert method returned by fromPath, fromBuffer, and fromBase64 functions.

    // v3.x way to get base64 response
    const convert = fromPath(filePath, options);
    const base64Response = convert(page, { responseType: 'base64' });
  5. Install pdf2pic

    master

    Install the pdf2pic utility via npm to convert PDFs to images, base64, or buffers.

    Prerequisites

    Before installing, ensure your environment meets these requirements:

    • Node.js version >= 14.x
    • graphicsmagick installed on the system
    • ghostscript installed on the system
    npm install --save pdf2pic
  6. Configure conversion options

    master

    The options object passed during initialization controls the output characteristics of the generated images.

    | option              | default value | description                                                                                                                                                                                                                                                        | 
    |---------------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 
    | quality             | `0`           | Image compression level. Value depends on `format`, usually from `0` to `100`                                                                                                                                                                                          | 
    | format              | `'png'`       | Formatted image characteristics / image format                                                                                                                                                                                                                    | 
    | width               | `768`         | Output width                                                                                                                                                                                                                                                      | 
    | height              | `512`         | Output height                                                                                                                                                                                                                                                     | 
    | preserveAspectRatio | `false`       | Maintains the aspect ratio of the image. When set to `true` and both `width` and `height` are specified, they are interpreted as the minimum width and minimum height, respectively.                                                                             | 
    | density             | `72`          | Output DPI (dots per inch)                                                                                                                                                                                                                                                        | 
    | savePath            | `'./'`        | Path where to save the output                                                                                                                                                                                                                                                    | 
    | saveFilename        | `'untitled'`  | Output filename                                                                                                                                                                                                                                                   | 
    | compression         | `'jpeg'`      | Compression method                                                                                                                                                                                                                                               | 
  7. Configure conversion response types

    master

    The convertOptions object determines the format of the data returned by the conversion process.

    optiondefault valuedescription
    responseTypeimageResponse type of the output. Accepts: image, base64 or buffer

    Note: Passing a boolean to responseType is deprecated and will be removed in the next major version:

    • true results in base64.
    • false results in image.
  8. Understand the ConvertResponse union type

    master

    The ConvertResponse type is a union that represents the output of a PDF conversion operation. Depending on the method used (writing to a file, converting to base64, or converting to a buffer), the response will match one of three specific interfaces. All response types inherit from BaseResponse, which provides common metadata about the conversion.

    Common Fields (BaseResponse)

    • size (optional string): The size of the resulting image.
    • page (optional number): The index of the PDF page that was converted.

    Response Variants

    1. WriteImageResponse: Returned when saving an image to a file. Includes name, fileSize, and path.
    2. ToBase64Response: Returned when converting to a base64 string. Includes the base64 string.
    3. BufferResponse: Returned when converting to a Node.js Buffer. Includes the buffer object.
    type ConvertResponse = WriteImageResponse | ToBase64Response | BufferResponse;
  9. Configure conversion output with ConvertOptions

    master

    When using the pdf2pic conversion methods, you can specify the desired output format using the responseType property in the options object. Supported values are:

    • 'image': Saves the result as an image file (returns WriteImageResponse).
    • 'base64': Returns the image as a base64 encoded string (returns ToBase64Response).
    • 'buffer': Returns the image as a Node.js Buffer (returns BufferResponse).
    // Example of specifying a response type
    const options = { responseType: 'base64' as const };
  10. Convert a specific PDF page to an image file

    master

    You can convert a single page from a PDF file path and save it directly to the filesystem using fromPath.

    To save as an image file, set the responseType in the conversion options to 'image'.

    import { fromPath } from "pdf2pic";
    
    const options = {
      density: 100,
      saveFilename: "untitled",
      savePath: "./images",
      format: "png",
      width: 600,
      height: 600
    };
    
    const convert = fromPath("/path/to/pdf/sample.pdf", options);
    const pageToConvertAsImage = 1;
    
    convert(pageToConvertAsImage, { responseType: "image" })
      .then((resolve) => {
        console.log("Page 1 is now converted as image");
        return resolve;
      });