Skip to content
sehrgutesoftwarePublic

About

Web service to create PDF files from HTML templates

Topics

Resources

Stars

2 stars

Watchers

2 watching

Forks

Repository files navigation

httpdf

PDF documents from HTML templates – as a web service

httpdf produces a PDF file from the following inputs:

  1. an HTML template, written in go's html/template syntax
  2. a JSON Schema describing the inputs required to render the template
  3. the actual template values as an HTTP POST request
  4. an optional ?lang= query parameter (or Accept-Language header) to select a translation file

It uses a headless Chromium or Firefox instance for PDF rendering, controlled via rod.

Templates and schemas are plain text files and therefore easily manageable. The web service can render any number of templates – chosen via a unique identifier in the URL path.

Usage

The web service can be run as a simple go binary or as a docker image.

Configuration

Settings are layered in the following order: Built-in defaults < config file < ENV < command line flags. All are optional, the server starts with no flags, no ENV and no config file at its default configuration.

Config File Environment Variable Flag Default Description
HTTPDF_CONFIG --config, -c Path of the config file.
listen HTTPDF_LISTEN --listen, -l :8080 Address to listen on.
templates HTTPDF_TEMPLATES --templates, -t templates Directory containing the templates, relative to the working directory, which is / in the docker image.
chromium HTTPDF_CHROMIUM --chromium /usr/bin/chromium-headless-shell Path of the Chromium binary, as installed in the docker image.
log.format HTTPDF_LOG_FORMAT json Log format written to stdout: json or text.
log.level HTTPDF_LOG_LEVEL info Minimum log level: trace, debug, info, warn or error. trace includes Chromium's output, which is useful for debugging the browser.
limits.maxRequestMB HTTPDF_MAX_REQUEST_MB 10 Maximum size of a render request's body in megabytes. Larger requests are rejected with 413.
limits.maxConcurrentRenders HTTPDF_MAX_CONCURRENT_RENDERS number of CPUs Maximum number of PDFs rendered at the same time. Further requests wait for a free slot.
limits.renderTimeout HTTPDF_RENDER_TIMEOUT 20s Maximum duration of a render, including the time spent waiting for a free slot, e.g. 20s or 1m. Keep it below 25 seconds, the time in-flight requests get to complete on shutdown.

A config file with all settings looks like this:

listen: ":8080"
templates: /templates
chromium: /usr/bin/chromium-headless-shell
log:
  format: json
  level: info
limits:
  maxRequestMB: 10
  maxConcurrentRenders: 4
  renderTimeout: 20s

API

POST /templates/{template}/render

Render the template using the JSON-encoded data provided in the request body. Successful response is of Content-Type: application/pdf. Templates are loaded on first use and cached in memory. In order to reload a template, the server must be restarted.

Response Status Codes
Code Meaning
200 Render success
400 Request body is not valid JSON
404 Template does not exist
413 Request body exceeds HTTPDF_MAX_REQUEST_MB
422 Request data does not match the template's schema
503 No render slot became available within HTTPDF_RENDER_TIMEOUT. Response contains a Retry-After header
504 Render did not complete within HTTPDF_RENDER_TIMEOUT
500 Unknown server error. Check the server logs and optionally open a bug report

GET /templates/{template}/preview

Render an HTML preview of the template using data from the template's example.json file. Useful for template development. The preview endpoint reads the template from disk on each request, so you can test changes without restarting the server.

GET /healthz

Health check endpoint for Kubernetes probes. Returns 200 OK as long as the HTTP server is running. Suitable for both liveness and readiness probes.

Template Development

Check the templates/example directory for an example template.

Templates are written in go's html/template syntax and can include any valid HTML. The template must be accompanied by a JSON Schema that describes the data structure required to render the template, as well as a configuration file defining the page layout.

Template Structure

Mount your templates into the container under the /templates directory. Each template is a folder by itself. The structure of the folder is as follows (file names must match exactly):

/templates
└── /example                # folder name = template name
    ├── template.html       # the HTML template itself
    ├── schema.json         # JSON Schema describing the data structure required by the template
    ├── config.yaml         # template config parameters
    ├── example.json        # (optional) example values
    ├── /partials           # (optional) additional template files
    ├── /assets             # (optional) static assets
    └── /locales/*.yaml     # (optional) translation files

The template is identified by its folder name. In the above example, the name of the template is example.

template.html itself must contain valid (= renderable by Chromium) HTML, using html/template as a templating language.

Values are escaped according to the context they're inserted into: HTML text, attribute values, URLs, CSS or JavaScript. This prevents request data from injecting markup or scripts into the page. Values that are unsafe in their context are replaced with ZgotmplZ, e.g. a data: URL in a src attribute or rgb(0, 0, 0) in a style attribute. To insert trusted values as they are, use the safeHTML, safeURL and safeCSS functions. HTML comments are removed from the output.

schema.json must be a valid JSON Schema according to Draft 2020-12. Its purpose is to validate the input data before populating the HTML template. Though not recommended, the schema can be empty (define an object with no properties). If your template is using placeholders that are not defined in the schema, you risk getting unclear errors during template rendering.

config.yaml contains configuration values related to the template. It has the following structure:

page:
    width: width of the resulting PDF in mm
    height: height of the resulting PDF in mm

locale: # optional
    locales:
    - en
    - de
    default: en

exposedEnvVars: # optional; list of env vars available in the template
    - IMAGE_PROXY_URL
    - LANG

pdf: # optional
    generateTaggedPDF: true # tag the PDF's structure for screen readers and other assistive technology
    generateDocumentOutline: true # add an outline (bookmarks) based on the HTML headings

Both pdf options default to false. Chromium derives the outline from the tags, so generateDocumentOutline implies generateTaggedPDF.

example.json can be added for testing and documentation purposes, providing some example data to render the template during template development.

partials/ is an optional directory for splitting complex templates into multiple files. Every .html file in it (including subdirectories) is parsed along with template.html and can be included by its path relative to partials/, e.g. {{ template "header.html" . }} or {{ template "sections/line-items.html" . }}. Templates declared with {{ define "name" }} in a partial are available in all files, and all template functions work in partials. Since all files share one namespace, a later definition of the same name replaces an earlier one. template.html is parsed first, followed by the partials in lexical order of their paths. This allows a partial to override a {{ block }} in template.html.

assets/ is an optional directory for static assets, such as images or stylesheets. They can be referenced in the HTML template using the asset function, e.g. <link rel="stylesheet" href="{{ asset "style.css" }}"> or <img src="{{ asset "images" "logo.png" }}">.

locales/ is an optional directory for translation files. Each file must be a valid YAML file containing key-value pairs for translations. The file names must match the language codes, e.g. en.yaml, de.yaml, etc. The translations can be accessed in the HTML template using the tr function, e.g. {{ tr "key" }}. The tr function will accept placeholders in the translation strings. The current locale can be accessed using {{ locale }}. See the example for usage.

Only translation files for the languages defined in the config.yaml file will be loaded.

Template Validation

In order to check templates for config or syntax errors, use httpdf-server validate. It exits with a non-zero status if any template is invalid. Without arguments, it validates all templates in the templates directory. httpdf-server validate invoice label validates only the named ones. This is useful as a build step in CI, when adding templates as a docker layer:

FROM ghcr.io/sehrgutesoftware/httpdf
COPY templates/ /templates/
RUN httpdf-server validate

Or as a stand-alone run:

docker run --rm -v ./templates:/templates ghcr.io/sehrgutesoftware/httpdf validate

It checks that:

  • all required files exist and can be read
  • schema.json is a valid JSON Schema
  • config.yaml can be loaded, contains no unknown keys, and the page width and height are greater than 0
  • template.html and all partials are free of syntax errors and only use existing functions
  • if locale is configured: locales isn't empty, contains the default locale, and each locale is a valid language tag with a translation file
  • if there's an example.json: it matches the schema and renders without errors
  • the server configuration is valid (see Configuration), because the server wouldn't start otherwise

If your image names a config file that's only mounted at runtime, skip it during the build with RUN HTTPDF_CONFIG= httpdf-server validate.

Invalid HTML output or errors in the PDF itself, such as missing assets or broken layouts, are not detected (no browser is run during validation).

The server runs the same validation on startup and logs a warning for each invalid template.

Template Functions

Base Functions
  • All Go template functions for basic operations
  • All Sprig functions for general template operations, except expandenv and getHostByName. Sprig's env is replaced by a restricted version, see below.
  • asset: Generate asset URLs with the configured assets prefix. Usage: {{ asset "style.css" }} or {{ asset "images" "logo.png" }}
  • chunk: Takes a list and returns a list of lists with n elements each, where n must be greater than 0. Usage: {{ chunk .items 2 }} or {{ chunk .items .columns }}
  • safeHTML, safeURL, safeCSS: Mark a value as trusted HTML, URL or CSS, so it's inserted without escaping. Never use them on values you don't trust, such as request data entered by end users. Usage: {{ tr "terms" | safeHTML }} or <img src="{{ .logo | safeURL }}">
Asset URL (asset function)

The asset function generates URLs for static assets with the configured assets prefix. This function takes one or more path segments and joins them with the assets prefix.

Example usage in template:

<link rel="stylesheet" href="{{ asset "style.css" }}">
<img src="{{ asset "images" "logo.png" }}" alt="Logo">
<script src="{{ asset "js" "lib" "jquery.js" }}"></script>
Internationalization Functions
  • locale: Returns the current locale string (e.g., "en", "de")
  • tr: Translates a key using the current locale with optional parameters
  • trLocale: Translates a key using a specific locale with optional parameters

Example usage in template:

<p>Current language: {{ locale }}</p>
<h1>{{ tr "welcome_message" "name" .userName }}</h1>
<p>German greeting: {{ trLocale "de" "hello" }}</p>
Environment Variables (env function)

The env function provides controlled access to environment variables within templates. For security reasons, only environment variables explicitly listed in the template's exposedEnvVars configuration can be accessed.

Example usage in template:

<p>Image proxy URL: {{ env "IMAGE_PROXY_URL" }}</p>
<p>Language: {{ env "LANG" }}</p>

If an environment variable is not in the exposed list or isn't set, the function returns an empty string. You can use the default function to provide fallback values.

QR Code Generation (qrCode function)

The qrCode function generates QR codes and returns them as base64-encoded PNG data URLs that can be directly embedded in HTML <img> tags. The function takes two parameters: size (in pixels) and the data to encode.

Example usage in template:

<!-- Generate a 128x128 pixel QR code for a URL -->
<img src="{{ qrCode 128 "https://example.com" }}" alt="QR Code">

<!-- Generate a QR code for text data -->
<img src="{{ qrCode 200 .contactInfo }}" alt="Contact QR Code">

<!-- Generate a QR code with default size (256x256) -->
<img src="{{ .data | qrCode 0 }}" alt="Data QR Code">

Parameters:

  • size (integer): Width and height of the QR code in pixels, at most 4096. If 0 or negative, defaults to 256 pixels. Can come from the request data, e.g. {{ qrCode .qrSize .url }}
  • data (string): The text data to encode in the QR code

The function returns a complete data URL string in the format data:image/png;base64,<encoded-data> that can be used directly as an image source.

The render fails if the data doesn't fit into a QR code (up to 2331 bytes of arbitrary text, more if it consists only of digits or uppercase letters), or if the size is smaller than the QR code's grid of modules (at least 21 pixels, more for longer data).

Changelog

Notable changes in each release, including how to migrate across breaking changes, are listed in CHANGELOG.md.

Development

In order to start the development server, employing hot-reload, use docker compose:

docker compose up

The container image includes a Chromium instance for HTML rendering. If you want to run the server directly in your host OS without using docker, tell it the path of a Chromium binary, e.g. on macOS:

go run ./cmd/server --chromium /Applications/Chromium.app/Contents/MacOS/Chromium

About

Web service to create PDF files from HTML templates

Topics

Resources

Stars

2 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages