Node.js HTML to Image Code Examples

These examples cover common HTML to Image tasks in server-side Node.js code. See the Node.js SDK guide for installation and result handling. For a download button without backend code, see WebSave as Image.

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

Importing the client

Examples use ES modules. For CommonJS, replace the import statements with require() and place awaited operations inside an async function.

CommonJS

const pdfcrowd = require('pdfcrowd');

TypeScript

The package includes TypeScript declarations. TypeScript infers conversion results and callback parameters from the SDK types. Use a namespace import:

import * as pdfcrowd from 'pdfcrowd';

For TypeScript compiled as CommonJS, you can also use:

import pdfcrowd = require('pdfcrowd');

When compiling a default import to CommonJS, enable esModuleInterop.

If your project needs Node.js types, see TypeScript dependency setup.

Basic examples

Choose file, in-memory, or output-stream handling for the PNG result. Stream examples use a file stream as their destination.

Convert a URL

Save to a file

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "example.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Keep in memory

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const image = await client.convertUrl("https://example.com/"); // Buffer
    console.log("Image ready:", image.length, "bytes");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Write to a stream

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const stream = await client.convertUrlToStream("https://example.com/");
    try {
        await pipeline(stream, fs.createWriteStream("example.png"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "example.png");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Convert an HTML file

Upload an existing document.html file. For local images and stylesheets, see Local assets.

Save to a file

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const filePath = await client.convertFileToFile(
        "document.html", "document.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Keep in memory

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const image = await client.convertFile("document.html"); // Buffer
    console.log("Image ready:", image.length, "bytes");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Write to a stream

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const stream = await client.convertFileToStream("document.html");
    try {
        await pipeline(stream, fs.createWriteStream("document.png"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "document.png");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Send HTML content

These examples read HTML text from document.html. In an application, pass the HTML produced by your template renderer instead.

Save to a file

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setOutputFormat("png");
    const filePath = await client.convertStringToFile(html, "html.png");
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Keep in memory

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setOutputFormat("png");
    const image = await client.convertString(html); // Buffer
    console.log("Image ready:", image.length, "bytes");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Write to a stream

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setOutputFormat("png");
    const stream = await client.convertStringToStream(html);
    try {
        await pipeline(stream, fs.createWriteStream("html.png"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "html.png");
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Convert inline HTML

Define a small HTML document directly in your code.

import pdfcrowd from 'pdfcrowd';

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

    client.setOutputFormat("png");
    const html = "<html><body><h1>Monthly Report</h1></body></html>";
    const filePath = await client.convertStringToFile(html, "report.png");
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Read from an input stream

Open document.html as a binary input stream and save the PNG to document.png.

import pdfcrowd from 'pdfcrowd';
import fs from 'node:fs';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const input_stream = fs.createReadStream("document.html");
    try {
        const filePath = await client.convertStreamToFile(
            input_stream, "document.png"
        );
        console.log("Saved:", filePath);
    } finally {
        input_stream.destroy();
    }
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Local assets

Include HTML and its local images, stylesheets, and scripts in a ZIP archive, keeping their relative paths.

Convert a prepared archive

Upload an existing document.zip. Select the main HTML file explicitly when the archive contains multiple documents.

Detect the main HTML file

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    const filePath = await client.convertFileToFile(
        "document.zip", "output.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Select index.html

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    client.setZipMainFilename("index.html");
    const filePath = await client.convertFileToFile(
        "document.zip", "document.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Convert a local directory

Create document.zip from the existing document directory, then convert it to PNG.

import pdfcrowd from 'pdfcrowd';
import AdmZip from 'adm-zip'; // npm install adm-zip

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

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

    const filePath = await client.convertFileToFile("document.zip", "document.png");
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Page rendering

Set screenshot width and scale

Capture a 1280-pixel-wide viewport and scale the PNG output to 50%.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    client.setScaleFactor(50);
    client.setScreenshotWidth(1280);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "customized.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Hide or restyle page elements

Replace the selectors with elements from your page.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setCustomCss(`
        /* Hide navigation, ads, and sidebar */
        nav, .advertisement, .sidebar, footer {
            display: none !important;
        }
        /* Adjust layout for screenshot */
        .content {
            width: 100% !important;
            max-width: none !important;
        }`);
    client.setOutputFormat("png");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "custom_css.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Modify the page with JavaScript

This example removes widgets and expands sections by changing their CSS classes. Adjust the selectors and class names for your page.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setCustomJavascript(`
        // Remove dynamic content before conversion
        document.querySelectorAll('.video-player, .chat-widget').forEach(el => {
            el.remove();
        });
        // Expand collapsed sections
        document.querySelectorAll('.collapsed').forEach(el => {
            el.classList.remove('collapsed');
        });`);
    client.setOutputFormat("png");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "custom_js.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Convert a specific element

Convert only #main in an existing document.html file. Adjust the filename and selector for your document.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setElementToConvert("#main");
    client.setOutputFormat("png");
    const filePath = await client.convertFileToFile(
        "document.html", "html_part.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Wait for a page element

Wait for #content-loaded to appear in an existing document.html file. Choose an element that appears when your content is ready.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    client.setWaitForElement("#content-loaded");
    const filePath = await client.convertFileToFile(
        "document.html", "wait_element.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Allow extra time for JavaScript

Add a delay of 2000 milliseconds. When the page has a reliable readiness marker, use Wait for a page element.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setJavascriptDelay(2000);
    client.setOutputFormat("png");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "with_delay.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Apply the page’s @media print rules. The page must provide print styles for this to change its appearance.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setOutputFormat("png");
    client.setUsePrintMedia(true);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "print_media.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

HTML and CSS

Add these fragments to HTML you control.

Remove or hide elements

<nav class="pdfcrowd-remove">This won't appear in the screenshot</nav>
<div class="pdfcrowd-hide">This is invisible but takes up space</div>

pdfcrowd-remove removes the element from the layout. pdfcrowd-hide preserves its space.

Apply styles only during conversion

<style>
  /* These styles only apply during image conversion */
  .pdfcrowd-body h1 { font-size: 48px; }
  .pdfcrowd-body footer { display: none; }
  .pdfcrowd-body .main-content { width: 100%; }
</style>

The .pdfcrowd-body prefix limits these rules to conversion; it does not change the page in a visitor’s browser.

Templates

Render a template with JSON data

Upload existing template.html and data.json files. See the template rendering guide for template syntax, data mapping, and other supported data formats.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToImageClient("demo", "demo");
    
    client.setDataFormat("json");
    client.setOutputFormat("png");
    client.setDataFile("data.json");
    const filePath = await client.convertFileToFile(
        "template.html", "output.png"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}