Generate PDFs in Express

Add a PDF download to an existing Express page, or generate a PDF from a template. This guide shows how to render EJS views in Express routes and use PDFCrowd's HTML to PDF API to return PDFs through Express's response handling.

Set up the client

Install the Node.js client in your Express application. The examples use the async/await interface available in SDK 7 and later:

npm install pdfcrowd

You can run the examples below with the included demo credentials, or replace them with your PDFCrowd username and API key.

Add a PDF download to an existing page

An existing page can display its usual HTML and return a PDF when the user clicks a download button. Reuse the page's template, data preparation, and access checks.

Choose what to send to PDFCrowd:

Convert rendered HTML

Add this handler where your application registers its document routes, using your existing app. The getDocumentForCurrentUser(req, documentId) function is a placeholder for your asynchronous document lookup and permission checks. Replace it with your own logic; it should reject missing or inaccessible documents. The EJS template at views/documents/detail.ejs receives the result as document.

Keep your authentication and CSRF middleware before these routes. The POST handler also expects express.urlencoded() to have parsed the form body.

const { promisify } = require('node:util');
const pdfcrowd = require('pdfcrowd');

async function documentDetail(req, res, next) {
    try {
        const { documentId } = req.params;
        if (!/^\d+$/.test(documentId)) return res.sendStatus(404);

        const document = await getDocumentForCurrentUser(req, documentId);
        if (req.method !== 'POST' || req.body?.download_pdf !== '1') {
            return res.render('documents/detail', { document });
        }

        const html = await promisify(res.render.bind(res))(
            'documents/detail', { document }
        );
        const client = new pdfcrowd.HtmlToPdfClient('demo', 'demo');
        client.setContentViewportWidth('balanced');
        const pdf = await client.convertString(html); // Buffer

        if (res.destroyed) return;
        res.attachment(`document-${documentId}.pdf`).type('pdf').send(pdf);
    } catch (error) {
        // Add your application's error handling here.
        next(error);
    }
}

app.route('/documents/:documentId')
    .get(documentDetail)
    .post(documentDetail);

Add this form to the EJS template, outside any existing form:

<form method="post" class="pdfcrowd-remove">
    <!-- Keep your application's CSRF token field here. -->
    <button type="submit" name="download_pdf" value="1">Download PDF</button>
</form>

Express does not include CSRF protection. Keep your application's token field in the form and its validation middleware on the POST route; the comment above is a placeholder for that field.

GET requests display the HTML page. Submitting the download button sends a POST, renders the same template, converts it, and returns a PDF download. Node's promisify() adapts res.render() so it can be awaited and returns HTML without sending a response. Binding it to res preserves the response's rendering context. The pdfcrowd-remove class hides the form in the PDF while leaving it visible on the webpage.

await client.convertString(html) returns the complete PDF as a Buffer held in memory. The handler then sends it as application/pdf; no PDF headers or bytes are sent before conversion succeeds.

The catch block forwards lookup, rendering, and conversion errors to Express through next(error). Keep production error responses generic and SDK details in server logs; do not use SDK error codes as HTTP response statuses. Set NODE_ENV=production when using Express's default error handler. See SDK error handling for details.

To display the PDF in the browser, replace res.attachment(...) with res.set('Content-Disposition', 'inline'). Set page size, margins, or other PDF options before convertString().

Make CSS and images available

PDFCrowd needs reachable URLs for stylesheets, images, and fonts referenced by the rendered HTML. Absolute asset URLs, such as https://your-site.example/css/document.css, need no additional base URL.

For relative paths, set the public site or directory URL in your application setup:

app.locals.pdfBaseUrl = 'https://your-site.example/';

Replace https://your-site.example/ with your website's public URL. Then add this to the EJS template's <head>, before stylesheet links:

<% if (typeof pdfBaseUrl !== 'undefined' && pdfBaseUrl) { %>
<base href="<%= pdfBaseUrl %>">
<% } %>

Express makes app.locals available to both res.render() and app.render(). The <base> therefore applies whenever this template is rendered, including the normal HTML page. It sets the base for relative assets and hyperlinks: css/document.css becomes https://your-site.example/css/document.css. For assets beneath a directory, use a base such as https://your-site.example/app/, including the trailing slash. Paths starting with / still resolve from the site's root. Avoid adding a second <base> if one already exists.

PDFCrowd cannot reach assets on your development machine through localhost or 127.0.0.1. For local assets, you can instead package the HTML and assets in a ZIP archive. Keep paths relative to the archive's folders and omit the website <base> for that approach.

Convert the page URL instead

Instead of sending rendered HTML, you can ask PDFCrowd to open the page through its URL. First configure your public origin in the application setup, without a path or trailing slash:

app.set('publicOrigin', 'https://your-site.example');

Keep the lookup, POST check, client setup, error handling, and response code above. Remove the const html = ... statement that renders the template and replace the convertString() line with:

const url = app.get('publicOrigin') + req.originalUrl;
const pdf = await client.convertUrl(url); // Buffer

This preserves the current path and query parameters while keeping the origin under your application's control. PDFCrowd makes a separate GET request, so the route returns HTML; only the original POST triggers conversion. The server must be able to handle that GET while the POST waits for the PDF. The page and its assets must be reachable from PDFCrowd.

The separate request does not inherit the user's Express session. For protected pages, configure cookies or HTTP authentication as appropriate, or use rendered HTML from the original request. If your session middleware locks the session until the POST finishes, forwarding that session can block the GET; use rendered HTML instead.

Generate a PDF from a template

You can also generate a PDF directly from a template and application data. Use an existing EJS template or a separate template designed for the document.

This async helper uses your configured Express app to render the template and returns a Promise that resolves to a PDF Buffer. It uses the same asset configuration as the route example:

const { promisify } = require('node:util');
const pdfcrowd = require('pdfcrowd');

async function renderPdf(app, template, context) {
    const html = await promisify(app.render.bind(app))(template, context);
    const client = new pdfcrowd.HtmlToPdfClient('demo', 'demo');
    client.setContentViewportWidth('balanced');
    return client.convertString(html);
}

For example, given a document, call it inside an async Express handler:

try {
    const pdf = await renderPdf(app, 'documents/pdf', { document });
    res.attachment('document.pdf').type('pdf').send(pdf);
} catch (error) {
    // Add your application's error handling here.
    next(error);
}

Here app is your configured application, and res and next come from the calling handler. Create views/documents/pdf.ejs for the document layout and pass all its data in context. Choose template names and context keys in application code; do not pass req.query or req.body directly as render options.

The helper sends no HTTP response. Its caller can use the buffer for a download, storage, or email. Rendering or conversion failures reject the Promise and reach the caller's catch block. Outside a request, pass the same configured app and use a template that does not depend on request-local values, such as session data or the download form's CSRF token.

For more conversion inputs and PDF settings, see the Node.js examples and API reference.