Image to Image in Node.js

Overview

Convert images between formats and resize, crop, or rotate them 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

You can run the examples below with the displayed API credentials. Update the input URLs and filenames as needed.

Convert an Image URL

Convert a PNG image to JPEG and save it locally as logo.jpg:

const pdfcrowd = require('pdfcrowd');

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

client.setOutputFormat("jpg");
client.convertUrlToFile(
    "https://your-server.com/logo.png", "logo.jpg",
    (error, filePath) => {
        if (error) {
            console.error(error.toString());
            return;
        }
        console.log("Saved:", filePath);
    }
);

The URL must return the image itself 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 an Image File

Convert logo.png to JPEG and save it locally as logo.jpg:

const pdfcrowd = require('pdfcrowd');

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

client.setOutputFormat("jpg");
client.convertFileToFile("logo.png", "logo.jpg", (error, filePath) => {
    if (error) {
        console.error(error.toString());
        return;
    }
    console.log("Saved:", filePath);
});

Configure a Conversion

Authentication

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

Choose an Input

The source image format is detected automatically. Each conversion accepts one image.

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

For a local image or a URL on localhost, upload the file, bytes, or an open binary stream. Remote URLs must be reachable from PDFCrowd's servers.

Send Image Bytes

Read logo.png as bytes, convert it to JPEG, and save logo.jpg:

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

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

client.setOutputFormat("jpg");
const image = fs.readFileSync("logo.png");
client.convertRawDataToFile(image, "logo.jpg", (error) => {
    if (error) {
        console.error(error.toString());
        return;
    }
});

Add Conversion Settings

Set conversion options on the client before calling a conversion method. For example, client.setOutputFormat("jpg"); selects JPEG output.

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

Image operations change the source image; canvas settings control the output area and image placement.

PurposeMethods
Resize or rotatesetResize(), setRotate()
Crop or remove solid-color borderssetCropArea(), setRemoveBorders()
Image resolution for layoutsetDpi()
Image formatsetOutputFormat()
Canvas dimensions and marginssetCanvasSize(), setCanvasDimensions(), setMargins(), setOrientation()
Image placement and backgroundsetPrintCanvasMode(), setPosition(), setCanvasBackgroundColor()

With an explicit canvas size, use setPrintCanvasMode() with "fit" to preserve the aspect ratio and fit the image inside the margins. The "stretch" mode fills the area and can distort the image. The default mode does not scale the image to fit and can crop it. Without an explicit size, margins add a border around the image.

Handle the Result

Choose an Output

The examples select JPEG. Use setOutputFormat() to choose PNG, WebP, or another supported format. The client defaults to PNG; match the filename extension to the selected format.

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

For stream output, pass a callbacks object with these functions:

CallbackWhen it runs
data(readStream) Called when the output stream is available. Read its chunks into a Buffer or pipe it to a writable stream.
error(message, statusCode) Called if the request or conversion fails. message describes the error; statusCode contains the error status code when available.
end() Called when all output data has been received.

If you pipe the response to a file, writing may still be in progress when end runs. Use the pipeline callback, after checking for errors, for code that uses the saved file.

This example converts an image, collects the result in a Buffer, and saves it locally as logo.jpg:

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

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

client.setOutputFormat("jpg");
const chunks = [];
client.convertUrl("https://your-server.com/logo.png", {
    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("logo.jpg", result);
    }
});

When serving the result from a web application, use Content-Type: image/jpeg for these examples, or the content type corresponding to your selected format.

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 an image and handles both paths, logging the HTTP status and reason code when available:

const pdfcrowd = require("pdfcrowd");

const client = new pdfcrowd.ImageToImageClient("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("jpg");
    client.convertUrlToFile(
        "https://your-server.com/logo.png", "logo.jpg",
        (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.
getOutputSize()Read the JPEG 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 an image 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.ImageToImageClient("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("jpg");
    client.setDebugLog(true);
    client.convertUrlToFile(
        "https://your-server.com/logo.png", "logo.jpg", 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 image cannot be loadedCheck that the URL returns an image, rather than HTML or a login page, and is reachable from PDFCrowd's servers. For local files, check the path and read permissions.
The image is distorted or croppedCheck dimensions, crop settings and margins. Use "fit" with setPrintCanvasMode() when setting an explicit output size.
The result looks blurryCheck the source image's pixel dimensions and how much it is enlarged. Increasing DPI cannot recover missing detail.
Transparency is lostJPEG does not support transparency. Select PNG and check whether the canvas background adds an opaque color.

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