PDF to Image in Node.js

Overview

Convert PDF pages to images with the PDFCrowd Node.js client. The client handles communication with the API, while conversions run on PDFCrowd's servers.

Installation

Install the Node.js client with npm, or see other installation options.

npm install pdfcrowd

Quick Start

Update the input URLs and filenames as needed.

Convert a PDF URL

Convert a PDF URL to PNG images and save them locally in invoice.zip:

const pdfcrowd = require('pdfcrowd');

const client = new pdfcrowd.PdfToImageClient("demo", "demo");

client.setForceZip(true);
client.setOutputFormat("png");
client.convertUrlToFile(
    "https://your-server.com/invoice.pdf", "invoice.zip",
    (error) => {
        if (error) {
            console.error(error.toString());
            return;
        }
    }
);

The URL must return a PDF and be reachable from PDFCrowd's servers. The output file is ready when the callback runs without an error. Put code that uses the file inside that callback. The callback receives a pdfcrowd.Pdfcrowd.Error on failure. Validation can also throw an exception. See Handle Errors.

Convert a PDF File

Convert invoice.pdf to PNG images and save them locally in invoice.zip:

const pdfcrowd = require('pdfcrowd');

const client = new pdfcrowd.PdfToImageClient("demo", "demo");

client.setForceZip(true);
client.setOutputFormat("png");
client.convertFileToFile("invoice.pdf", "invoice.zip", (error) => {
    if (error) {
        console.error(error.toString());
        return;
    }
});

Configure a Conversion

Authentication

Pass your PDFCrowd username and API key to PdfToImageClient. Find your credentials on the API Keys page.

Choose an Input

Send a PDF URL, upload a local file, or pass PDF bytes or a readable binary stream.

InputMethod
URLconvertUrlToFile()
Local fileconvertFileToFile()
Bytes in memoryconvertRawDataToFile()
Readable binary streamconvertStreamToFile()

Add Conversion Settings

Set conversion options on the client before calling a conversion method. For example, client.setDpi(150); renders PDF pages at 150 DPI.

Common settings are listed below. See the method reference for all available options or browse Node.js examples.

PurposeMethods
Pages to convertsetPrintPageRange()
Password-protected inputsetPdfPassword()
Image format and resolutionsetOutputFormat(), setDpi()
Consistent ZIP outputsetForceZip()
Crop areasetUseCropbox(), setCropArea()
GrayscalesetUseGrayscale()

Higher DPI produces larger images and files. PNG is the default image format.

The PDF password unlocks the input document; it is separate from your PDFCrowd API key.

Handle the Result

Choose an Output

A single converted page produces an image; multiple pages produce a ZIP archive containing an image for each page. The examples use setForceZip() to always return a ZIP archive, including for a single page.

The methods below use URL input; local files, bytes, and input streams have corresponding methods.

OutputMethod
Local fileconvertUrlToFile()
Readable streamconvertUrl(), with a data(stream) callback

The data callback receives the response stream. Pipe it to a writable stream or collect its chunks in a Buffer. The end callback runs when the response finishes.

This example converts PDF pages to PNG images in a ZIP archive, collects the result in a Buffer, and saves it locally as invoice.zip:

const fs = require("node:fs");
const pdfcrowd = require("pdfcrowd");

const client = new pdfcrowd.PdfToImageClient("demo", "demo");

client.setOutputFormat("png");
client.setForceZip(true);
const chunks = [];
client.convertUrl("https://your-server.com/invoice.pdf", {
    data: (stream) => stream.on("data", (chunk) => chunks.push(chunk)),
    error: (message, statusCode) => {
        console.error(new pdfcrowd.Pdfcrowd.Error(message, statusCode).toString());
    },
    end: () => {
        const result = Buffer.concat(chunks);
        fs.writeFileSync("invoice.zip", result);
    }
});

After conversion, isZippedOutput() indicates whether the result is a ZIP archive. Match the output filename and content type to the result: .zip and application/zip for archives, or .png and image/png for a single PNG.

Handle Errors

File-output methods pass a pdfcrowd.Pdfcrowd.Error to their callback on failure and null on success. Validation can also throw an exception. This example converts PDF pages to PNG images in a ZIP archive and handles both paths, logging the HTTP status and reason code when available:

const pdfcrowd = require("pdfcrowd");

const client = new pdfcrowd.PdfToImageClient("demo", "demo");

function handleError(error) {
    if (error instanceof pdfcrowd.Pdfcrowd.Error) {
        console.error("PDFCrowd error:", error.getStatusCode(),
            error.getReasonCode(), error.getMessage());
    } else {
        console.error(error);
    }
}

try {
    client.setOutputFormat("png");
    client.setForceZip(true);
    client.convertUrlToFile(
        "https://your-server.com/invoice.pdf", "invoice.zip",
        (error) => {
            if (error) {
                handleError(error);
                return;
            }
        }
    );
} catch (error) {
    handleError(error);
}

Stream-output methods call error(message, statusCode) on failure. Local file and stream errors may need separate handling.

pdfcrowd.Pdfcrowd.Error provides these methods:

MethodReturns
getStatusCode()The HTTP status code, when available.
getReasonCode()The reason code identifying the specific error, or -1 if unavailable.
getMessage()The error message.
getDocumentationLink()A link to relevant documentation, when available.

error.toString() returns the complete error, including available status and reason codes.

Common Status Codes

StatusWhat it meansWhat to do
400Invalid input, settings, or conversion failureRead the reason code and correct the input or settings.
401Missing credentials or an inactive licenseCheck your username, API key, and license status.
403Suspended service or no credits remainingCheck your account and available credits.
413Upload exceeds the 300 MB limitReduce the upload size.
429Request rate limit reachedWait and reduce the rate of new requests.
430Concurrent request limit reachedAllow active requests to finish before starting more.
503Temporary network issueCheck your retry policy before submitting another request.

See all status and reason codes for specific explanations and Limits and Retries for retry behavior.

Read Conversion Information

This information is available after a conversion and describes the client's last conversion. Read it in the completion or error callback.

MethodUse
getJobId()Identify the conversion in logs and support requests.
getDebugLogUrl()The URL of the conversion debug log when logging is enabled.
getPageCount()Read the page count reported for the conversion.
getOutputSize()Read the output size in bytes.
getConsumedCreditCount()Read the credits consumed by the conversion.
getRemainingCreditCount()Read the remaining credit count reported with the conversion.

Limits and Retries

Request rate and concurrency limits depend on your license. Control how quickly your application submits conversions and how many it runs at once. A 429 response concerns request rate; a 430 response concerns requests already in progress. The maximum upload size is 300 MB.

The Node.js client automatically retries a request once when it receives HTTP 502 or 503. Use setRetryCount() to change that count, or set it to 0 to disable automatic retries. Account for these retries when adding an application-level retry policy.

Troubleshooting

Inspect a Conversion

This example converts PDF pages to PNG images in a ZIP archive with debug logging enabled and logs the debug log URL when available. Use the input and settings from the conversion you are investigating.

const pdfcrowd = require("pdfcrowd");

const client = new pdfcrowd.PdfToImageClient("demo", "demo");

function finish(error) {
    if (error) {
        console.error(error.toString());
    }
    const debugLogUrl = client.getDebugLogUrl();
    if (debugLogUrl) console.info("Debug log:", debugLogUrl);
}

try {
    client.setOutputFormat("png");
    client.setForceZip(true);
    client.setDebugLog(true);
    client.convertUrlToFile(
        "https://your-server.com/invoice.pdf", "invoice.zip", finish
    );
} catch (error) {
    finish(error);
}

The debug log contains conversion settings and processing details. You can also find logs in your conversion history. A local or connection failure may occur before a conversion log is available.

Common Problems

ProblemCheck
The PDF cannot be loadedCheck that the URL returns a PDF, rather than HTML or a login page, and is reachable from PDFCrowd's servers. For local files, check the path and read permissions.
The PDF requires a passwordSet the input document's password with setPdfPassword().
The result cannot be opened as an imageMultiple pages produce a ZIP archive. Check isZippedOutput() and extract the images.
Images look blurry or are too largeAdjust setDpi(). Enlarging raster content cannot recover detail missing from the source.

For help, contact support and include any available diagnostics, the client version, and enough detail to reproduce the problem.