Skip to content

The ctx.renderPdf() method

Cédric Belin edited this page Oct 18, 2024 · 11 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 viewData = {message: "Hello World!"};
  return ctx.renderPdf("view", viewData);
});

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 Puppeteer project and the Chromium web browser.

What does this mean? 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 PuppeteerNode.launch() method provided by Puppeteer. For example, use it to customize which browser will be used to render PDF documents.

// Use Chrome Canary instead of Chromium.
eta(app, {
  browser: {channel: "chrome-canary"},
  views: join(import.meta.dirname, "path/to/view/folder")
});

Please refer to the Puppeteer 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 Puppeteer.

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

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

Clone this wiki locally