Node.js HTML to PDF Code Examples

These examples cover common HTML to PDF 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 PDF.

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 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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "example.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const pdf = await client.convertUrl("https://example.com/"); // Buffer
    console.log("PDF ready:", pdf.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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const stream = await client.convertUrlToStream("https://example.com/");
    try {
        await pipeline(stream, fs.createWriteStream("example.pdf"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "example.pdf");
} 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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const filePath = await client.convertFileToFile(
        "document.html", "document.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const pdf = await client.convertFile("document.html"); // Buffer
    console.log("PDF ready:", pdf.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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const stream = await client.convertFileToStream("document.html");
    try {
        await pipeline(stream, fs.createWriteStream("document.pdf"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "document.pdf");
} 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.HtmlToPdfClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setContentViewportWidth("balanced");
    const filePath = await client.convertStringToFile(html, "html.pdf");
    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.HtmlToPdfClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setContentViewportWidth("balanced");
    const pdf = await client.convertString(html); // Buffer
    console.log("PDF ready:", pdf.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.HtmlToPdfClient("demo", "demo");
    
    const html = fs.readFileSync("document.html", 'utf8');
    client.setContentViewportWidth("balanced");
    const stream = await client.convertStringToStream(html);
    try {
        await pipeline(stream, fs.createWriteStream("html.pdf"));
    } finally {
        stream.destroy();
    }
    console.log("Saved:", "html.pdf");
} 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.HtmlToPdfClient("demo", "demo");

    client.setContentViewportWidth("balanced");
    const html = "<html><body><h1>Monthly Report</h1></body></html>";
    const filePath = await client.convertStringToFile(html, "report.pdf");
    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 PDF to document.pdf.

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

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const input_stream = fs.createReadStream("document.html");
    try {
        const filePath = await client.convertStreamToFile(
            input_stream, "document.pdf"
        );
        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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    const filePath = await client.convertFileToFile(
        "document.zip", "output.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setZipMainFilename("index.html");
    const filePath = await client.convertFileToFile(
        "document.zip", "document.pdf"
    );
    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 PDF.

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

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

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

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

Create an archive in memory

Package the existing document directory in memory. Its index.html file can refer to other files in the directory by relative path.

import pdfcrowd from 'pdfcrowd';
import { Readable } from 'node:stream';
import AdmZip from 'adm-zip'; // npm install adm-zip

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

    client.setContentViewportWidth("balanced");
    client.setZipMainFilename("index.html");
    const archive = new AdmZip();
    archive.addLocalFolder("document");
    const archive_bytes = archive.toBuffer(); // Buffer
    const input_stream = Readable.from([archive_bytes]);
    try {
        const filePath = await client.convertStreamToFile(input_stream, "document.pdf");
        console.log("Saved:", filePath);
    } finally {
        input_stream.destroy();
    }
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Page rendering

Set page size and margins

Use landscape Letter pages with half-inch margins.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setMarginBottom("0.5in");
    client.setMarginLeft("0.5in");
    client.setMarginRight("0.5in");
    client.setMarginTop("0.5in");
    client.setOrientation("landscape");
    client.setPageSize("Letter");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "page-layout.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Add a header and page numbers

Show the source URL in the header and “Page N of M” in the footer.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setFooterHeight("10mm");
    client.setFooterHtml(`
        <center>
            Page <span class="pdfcrowd-page-number"></span>
            of <span class="pdfcrowd-page-count"></span>
        </center>`);
    client.setHeaderHeight("15mm");
    client.setHeaderHtml(`
        <a class="pdfcrowd-source-url"
            data-pdfcrowd-placement="href-and-content"></a>`);
    client.setMarginBottom("0");
    client.setMarginTop("0");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "header_footer.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

See the headers and footers guide for more layouts and placeholders.

Scale page content

Scale the HTML content to 300%.

import pdfcrowd from 'pdfcrowd';

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

Choose a responsive layout

The browser viewport controls responsive breakpoints independently of the PDF paper size.

Large viewport

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("large");
    client.setNoMargins(true);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "bootstrap.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Small viewport

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("small");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "viewport_small.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setCustomCss(`
        /* Hide navigation, ads, and sidebar */
        nav, .advertisement, .sidebar, footer {
            display: none !important;
        }
        /* Adjust layout for print */
        .content {
            width: 100% !important;
            max-width: none !important;
        }`);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "custom_css.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Modify the page with JavaScript

Adjust the selectors and class names for your page.

Remove widgets and expand sections

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    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');
        });`);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "custom_js.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Add content to the page

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setCustomJavascript(`
        el = document.createElement('h2');
        el.textContent = 'Hello from PDFCrowd API';
        el.style.color = 'red';
        el_before = document.getElementsByTagName('h1')[0];
        el_before.parentNode.insertBefore(el, el_before.nextSibling);`);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "html_inject.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setElementToConvert("#main");
    const filePath = await client.convertFileToFile(
        "document.html", "html_part.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setWaitForElement("#content-loaded");
    const filePath = await client.convertFileToFile(
        "document.html", "wait_element.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setJavascriptDelay(2000);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "with_delay.pdf"
    );
    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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setUsePrintMedia(true);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "print_media.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Inspect element boundaries

Highlight element boxes to investigate spacing and layout.

Highlight backgrounds

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setCustomJavascript(`
        libPdfcrowd.highlightHtmlElements({
            backgroundColor: 'rgba(255, 191, 0, 0.1)',
            borderColor: null
        });`);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "highlight_background.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Add borders and spacing

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setCustomJavascript(`
        libPdfcrowd.highlightHtmlElements({
            borderColor: 'orange',
            backgroundColor: null,
            padding: '4px',
            margin: '4px'
        });`);
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "highlight_borders.pdf"
    );
    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 PDF</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.

Control page breaks

<!-- Force a page break before the following section -->
<div style="page-break-before: always"></div>

<!-- Avoid breaking tables across pages -->
<style>
  table, tr, td { page-break-inside: avoid; }
</style>

Content taller than a page still needs to break.

Apply styles only during conversion

<style>
  /* These styles only apply during PDF 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.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setDataFormat("json");
    client.setDataFile("data.json");
    const filePath = await client.convertFileToFile(
        "template.html", "output.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

PDF features

Create a fillable PDF

Use an existing form.html file containing HTML form controls.

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setContentViewportWidth("balanced");
    client.setEnablePdfForms(true);
    const filePath = await client.convertFileToFile("form.html", "form.pdf");
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

See fillable PDF forms for supported controls and attributes.

Set PDF metadata

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setAuthor("PDFCrowd");
    client.setKeywords("PDFCrowd,demo");
    client.setSubject("Demo");
    client.setTitle("Hello World");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "with_metadata.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

Set a presentation view

import pdfcrowd from 'pdfcrowd';

try {
    const client = new pdfcrowd.HtmlToPdfClient("demo", "demo");
    
    client.setInitialZoomType("fit-page");
    client.setNoMargins(true);
    client.setOrientation("landscape");
    client.setPageLayout("single-page");
    client.setPageMode("full-screen");
    const filePath = await client.convertUrlToFile(
        "https://example.com/", "slide_show.pdf"
    );
    console.log("Saved:", filePath);
} catch (error) {
    // Handle the error in your application.
    console.error(String(error));
}

These settings request a full-screen initial view with landscape pages. The PDF viewer controls whether it honors those preferences.