Skip to content

The ctx.renderPdf() method

Cédric Belin edited this page Jan 30, 2025 · 20 revisions

This method lets you render an Eta template in HTML format as a PDF document and send it as HTTP response. Its signature and usage are basically the same as those of the ctx.render() method, except that it returns a Buffer instead of a string.

import {eta} from "@cedx/koa-eta";
import Koa from "koa";
import {join} from "node:path";

const app = new Koa;
eta(app, {views: join(import.meta.dirname, "path/to/view/folder")});

app.use(async ctx => {
  const locals = {message: "Hello World!"};
  await ctx.renderPdf("view", locals);
});

Note

The content type of the HTTP response will automatically be set to application/pdf.

Setup

To render view templates as PDF documents, this library relies on the Playwright project and the Chromium web browser.

What does this mean? First of all, you need to make sure that Chromium is correctly installed. To do this, run the following command in a terminal:

npx playwright install --with-deps chromium

Secondly, you need to be aware that this rendering method is heavy in terms of memory consumption and CPU usage. Your server must therefore be sufficiently sized to accept such a load.

Caution

It's not suitable for high-traffic websites! It's preferable to consider setting up a caching system of some kind to avoid having to render the same PDF every time your server receives a request.

The eta() function accepts a browser option which is an object that is directly passed to the BrowserType.launch() method provided by Playwright. For example, use it to customize which browser will be used to render PDF documents.

// Use Microsoft Edge instead of Chromium.
eta(app, {
  browser: {channel: "msedge"},
  views: join(import.meta.dirname, "path/to/view/folder")
});

Please refer to the Playwright documentation for details of all configuration settings supported by the browser option.

Rendering options

The ctx.renderPdf() method supports the same options as the ctx.render() method (i.e. async and writeResponse).

Other options are available to specifically customize the PDF rendering. These options are specified in the ctx.renderPdf() call and passed directly to the Page.pdf() method provided by Playwright.

app.use(async ctx => {
  const locals = {message: "Hello World!"};
  await ctx.renderPdf("view", locals, {
    format: "A4",
    outline: true
  });
});

Please refer to the Playwright documentation for details of all configuration options supported by the PDF rendering.

Clone this wiki locally