HTML to Image in Node.js

Overview

Convert web pages and HTML documents 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 URL

Convert a web page to PNG and save it locally as example.png:

const pdfcrowd = require('pdfcrowd');

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

client.setOutputFormat("png");
client.convertUrlToFile("https://example.com/", "example.png", (error) => {
    if (error) {
        console.error(error.toString());
        return;
    }
});

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 HTML File

Upload document.html and save the converted PNG locally as document.png:

const pdfcrowd = require('pdfcrowd');

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

client.setOutputFormat("png");
client.convertFileToFile("document.html", "document.png", (error) => {
    if (error) {
        console.error(error.toString());
        return;
    }
});

For HTML that references local images or stylesheets, see Include Local Assets. To pass an HTML string, see Send HTML Content.

Configure a Conversion

Authentication

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

To load a protected source website, configure its website credentials, cookies, or HTTP headers separately.

Choose an Input

InputMethod
Web page URLconvertUrlToFile()
HTML stringconvertStringToFile()
Local HTML file or archiveconvertFileToFile()

URLs must be reachable from PDFCrowd's servers. For a page on localhost, send its HTML content or upload a file. Referenced assets must also be reachable from PDFCrowd's servers or included in an archive.

Send HTML Content

Convert an HTML string to PNG and save it as report.png:

const pdfcrowd = require("pdfcrowd");

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

const html = "<html><body><h1>Monthly Report</h1></body></html>";
client.setOutputFormat("png");
client.convertStringToFile(html, "report.png", (error) => {
    if (error) {
        console.error(error.toString());
        return;
    }
});

Replace html with the output of your template renderer. For relative resource URLs, add a <base href="https://example.com/"> element to the HTML head, or use absolute URLs. PDFCrowd can also combine an HTML template with structured data; see HTML templates.

Include Local Assets

Package the HTML and its local images, CSS, and JavaScript in a .zip, .tar.gz, or .tar.bz2 archive. Preserve the relative paths used by the HTML.

This example packages the HTML file and its local assets from a directory named document into document.zip, then converts the HTML to document.png:

const AdmZip = require("adm-zip"); // npm install adm-zip
const pdfcrowd = require("pdfcrowd");

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

const archive = new AdmZip();
archive.addLocalFolder("document");
archive.writeZip("document.zip");

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

The API automatically converts the first HTML file it finds in the archive. If the archive contains multiple HTML files, use setZipMainFilename() to choose which one to convert.

Add Conversion Settings

Set conversion options on the client before calling a conversion method. For example, client.setScreenshotWidth(1280); sets the screenshot width to 1280 pixels.

Common settings are listed below. See the method reference for all available options, browse Node.js examples, or try settings in the API Playground.

PurposeMethods
Image formatsetOutputFormat()
Screenshot dimensions and scalingsetScreenshotWidth(), setScreenshotHeight(), setScaleFactor()
Background colorsetBackgroundColor()
Print styles and custom CSSsetUsePrintMedia(), setCustomCss()
JavaScript and readinesssetCustomJavascript(), setWaitForElement(), setJavascriptDelay()
Convert a specific elementsetElementToConvert()

The default screenshot width is 1024 pixels. When no height is set, the image uses the document height.

Handle the Result

Choose an Output

The default output format is PNG. Use setOutputFormat() with "jpg" for JPEG, or select another supported format from the method reference. Match the output filename extension to the selected format.

The methods below use URL input; HTML strings and files 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 a web page, collects the result in a Buffer, and saves it locally as example.png:

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

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

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

When serving the image from a web application, use the corresponding content type, such as image/png or image/jpeg.

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

const pdfcrowd = require("pdfcrowd");

const client = new pdfcrowd.HtmlToImageClient("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.convertUrlToFile("https://example.com/", "example.png", (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 image 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 maximum size for any created image is 65 megapixels. Images exceeding this size are cropped vertically to meet this limit.

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.

PDFCrowd stops a conversion that exceeds 60 seconds of processing time. Reason code 323 identifies this HTML conversion timeout. Check for slow resource downloads or long-running JavaScript. Allowing your application to wait longer does not extend the server's processing limit.

Troubleshooting

Inspect a Conversion

This example converts a web page 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.HtmlToImageClient("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.setDebugLog(true);
    client.convertUrlToFile("https://example.com/", "example.png", finish);
} catch (error) {
    finish(error);
}

The debug log includes resource-loading details, timeouts, and browser console messages. 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
Images or styles are missingCheck resource URLs and authentication. See Include Local Assets for local resources.
A login page appears in the outputCheck the source website's authentication.
Dynamic content is missingUse setWaitForElement() or setJavascriptDelay(), and inspect the debug log.
The image has unexpected dimensions or is croppedCheck setScreenshotWidth(), setScreenshotHeight(), and the image size limit.
The image needs different stylingUse setCustomCss() to hide or restyle elements.
The application times out before receiving a resultCheck client and application timeouts. Allow for uploading the input, conversion, and downloading the result.

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