- Python 80.9%
- Lua 16.8%
- Shell 1%
- HTML 0.8%
- Dockerfile 0.4%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .github | ||
| .sonarlint | ||
| app | ||
| corpus | ||
| filters | ||
| fonts | ||
| monitoring | ||
| tests | ||
| tools | ||
| warmup | ||
| .gitignore | ||
| .pre-commit-config.yaml | ||
| .tool-versions | ||
| CHANGELOG.md | ||
| CLAUDE.md | ||
| CODING_STANDARDS.md | ||
| CONTRIBUTING.md | ||
| DCO | ||
| docker-compose.yaml | ||
| Dockerfile | ||
| entrypoint.sh | ||
| healthcheck.sh | ||
| LICENSE | ||
| NOTICE | ||
| pyproject.toml | ||
| README.md | ||
| RELEASE.md | ||
| renovate.json | ||
| sonar-project.properties | ||
| tox.ini | ||
| uv.lock | ||
| zizmor.yml | ||
Pandoc Service
A Dockerized service providing a REST API interface to leverage Pandoc's functionality for converting documents from one format into another.
Features
- Simple REST API to access Pandoc
- Direct subprocess calls to the pandoc binary (no Python module dependency)
- Embedded SVG diagrams drawn with weasysvg, vector where the target allows it, so SVGs (e.g. draw.io / mxgraph) render correctly in targets with weak SVG support such as Word
- Prometheus metrics endpoint on dedicated port (9182) for monitoring and Grafana integration
- Compatible with amd64 and arm64 architectures
- Easily deployable via Docker
Getting Started
Installation
To install the latest version of the Pandoc Service, run the following command:
docker pull ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
Running the Service
To start the Pandoc service container, execute:
docker run --init --detach \
--publish 9082:9082 \
--publish 9182:9182 \
--name pandoc-service \
--env REQUEST_BODY_LIMIT_MB=500 \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
The service will be accessible on port 9082, and Prometheus metrics on port 9182.
The REQUEST_BODY_LIMIT_MB environment variable sets the maximum allowed size (in megabytes) for uploaded files or request bodies processed by the Pandoc service. The default is 500 MB.
SVG conversion
For HTML sources, the service prepares embedded SVGs before handing the HTML to
pandoc. Microsoft Word does not draw draw.io's <switch> / <foreignObject>
mechanism and would otherwise show the "Text is not SVG - cannot display" fallback
instead of the diagram.
weasysvg draws the SVG and keeps it vector where the target allows it (see the table below). The service runs no browser.
This runs only for source_format == "html". It is best effort: if the drawing
fails, conversions still run and SVGs are passed through unchanged. The service
never fails because of it.
Image density (scale factor). The rasterization density is controlled by a
device scale factor (1.0 = 96 dpi). It can be set per request with the
scale_factor query parameter on the conversion endpoints, or globally via the
DEVICE_SCALE_FACTOR environment variable; the query parameter takes precedence,
falling back to the env var, then to 1.0. The docx-exporter extension sends
this as its "Image density" setting (96/192/300/600 dpi → 1.0/2.0/3.125/6.25).
The size the document gives. An image is drawn at the size its style states
(width and/or height, in any unit which says how long it is on its own: px,
in, cm, mm, pt, pc, or a bare number read as px), and the SVG is rasterized
at that size times the scale factor, so the drawing stays sharp wherever it is
enlarged. Where the document states one side, the other follows the ratio of the SVG.
Where it states no size a length can be read from, the SVG's own size is the one
drawn. A percentage is the one thing left to the target: it is a share of a width only
the target knows.
max-width and max-height hold the size. Where the document states both sides it has
chosen the shape already, so each side is held by the cap on its own axis and by no
other. Where it states one side and leaves the other to the drawing, a cap catching
either makes both give way together, so the drawing keeps its shape instead of sitting
in a box of empty space. Where it states no size at all, both sides follow the drawing
and a cap shrinks the whole of it.
The size is written onto the <img> as a width/height attribute, which is what
the writer of every target reads. Rasterization alone is capped, at 10000 px a side
and 50 megapixels counted after the scale factor: beyond that the PNG is made at the
size of the SVG, and the image is still drawn at the size the document gives.
Vector SVG. The SVG stays vector where the target allows it:
| Target | What the document gets |
|---|---|
docx |
The PNG drawn by weasysvg, and on top of it the flat SVG of weasysvg-convert -f svg, as Word saves an SVG. Word 2016 and later draws the vector, an older Word the PNG. The flat SVG holds only paths, clips, gradients and opacities, which Word draws. With svg_in_docx=false the document gets the PNG alone, at the density of scale_factor: the conversion is faster, and Word shows a large drawing at once. |
pdf, latex |
The SVG as it is. pandoc converts it with rsvg-convert, which is weasysvg-convert under that name: the PDF gets the SVG as vector, with its text. |
html, epub |
The SVG as it is, which a browser draws. |
| other targets | The PNG drawn by weasysvg. |
The scale factor sets the density of the PNG only. Earlier releases drew every SVG
as a PNG through Chromium and chose with SVG_RENDERER; any other value than
weasysvg is now logged as no longer supported and ignored.
Configuration (environment variables):
| Variable | Default | Range | Purpose |
|---|---|---|---|
ENABLE_SVG_CONVERSION |
true |
- | Master switch for the SVG preprocessing. |
DEVICE_SCALE_FACTOR |
1.0 |
1.0-10.0 | Rasterization density (overridden per request by scale_factor). |
The SVG drawings run under the conversion limit of MAX_CONCURRENT_PANDOC_CONVERSIONS.
MAX_CONCURRENT_CONVERSIONS and the CHROMIUM_* variables of earlier releases have no effect.
An out-of-range or invalid DEVICE_SCALE_FACTOR falls back to the default with a warning logged.
docker run --init --detach \
--publish 9082:9082 \
--publish 9182:9182 \
--name pandoc-service \
--env DEVICE_SCALE_FACTOR=2.0 \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
The /health and /version endpoints report svgRenderer, always weasysvg, and
/version reports the weasysvg version and the weasyprint version it draws with.
Inline CSS in HTML to DOCX
Pandoc's DOCX writer ignores the style attribute of an HTML element. For an html to docx
conversion, filters/html/inline_styles.lua carries the inline CSS across instead:
| Element | CSS the DOCX keeps |
|---|---|
<span> |
font-weight, font-style, text-decoration, color, background-color, font-size, font-family |
<h1>..<h6>, <div> |
a bold font-weight (bold, bolder, or 600 and more) |
<p>, <div> |
margin-left and text-align, as the indent and justification of the paragraph |
<img> |
width and height; vertical-align and margin-left/margin-right on an inline image |
<td>, <th> |
background-color, borders and vertical-align, with preserve_table_styles=true |
A bold <div> makes everything inside it bold, lists, table cells and nested divs included, until an
element declares a font-weight of its own. That is how a browser renders it. The color of a <span> is read in
hex or rgb() notation only; a named color such as red is dropped.
An inline image takes vertical-align as bottom, text-bottom, middle or an absolute length, and an
absolute, non-negative margin. The keywords use estimated font metrics of the text next to the image:
bottom and text-bottom lower the image by a descent of a quarter of the font size, and middle centers it
a quarter of the font size above the baseline. Other keywords are not mapped, and the image stays on the baseline.
An anchor (<a id>, or a <span> with an id) stays a bookmark in the DOCX, also inside styled text,
so a link to it still jumps there.
DOCX to PDF
A PDF of a DOCX takes these from the document, so it lays the text out closer to Word:
| From the DOCX | In the PDF |
|---|---|
<w:pgSz> and <w:pgMar> of the first section |
the page size and margins of the first pages; US Letter with 1 inch margins without them |
| the font of the Body Text style, else Normal, else the defaults, also as a theme font | the font of the body text, when the container has it or the font which stands for it, see below |
| the font size and line spacing of that style | the size, and the line the font sets: its ascent, descent and line gap, as Word reads them; spaces neither shrink nor widen after a full stop, and neither the ligatures of TeX nor of the font; a line breaks after a hyphen as freely as after a space, and the full stop which ends a paragraph may stand in the margin; no line of a paragraph alone at the top or bottom of a page, and a page ends where the descent of its last line reaches the bottom margin |
| the space before and after of that style | the space between paragraphs: the larger of the two, as Word lays it out |
<w:jc> of that style, and <w:autoHyphenation> |
ragged right and unhyphenated, unless the style justifies and the document hyphenates |
<w:rFonts> of a run |
the font of the run, when the container has it or the font which stands for it, matched regardless of case; a paragraph of runs in one font and size alone gets the line of that font |
| a space at the start or the end of a run of other formatting | the formatting of that run: struck through, underlined, and as wide as its font and size make it, as Word draws it |
| the Title and Heading 1 to 9 styles | the font, size, colour, italics, alignment and space of the title and the headings, the title as far down the page as the ascent of its font and the next line below its descent, the number of a heading style with numbering, all nine levels of them, as Word has them; between two headings only their own space |
| the Hyperlink style of the runs of a link, a theme colour as Word reads it | the colour of those runs; a link without it in the colour of its text |
| a table of a style without borders, and the Compact style of its cells | no lines but the one under a header row, rows as tall as Word's, and the cell margins of the default table style |
| a cell paragraph without a style | rows as tall as a paragraph of the Normal style, its text at the top and the space below it, as Word sets them |
a table whose cells draw every side, <w:tcBorders> or <w:tblBorders> |
a grid of lines in their colour and width, none inside a merged cell, the table out to the cell margin; a table with a picture, a list or a note in a cell keeps LaTeX's rules |
| a cell with sides of its own: a style, width or color other than the rest of the grid | each side as Word draws it: single, dashed, dotted or double, a line between rows as high as its widest piece; a dashed or dotted vertical side as a single line |
| a row of a table taller than the rest of the page | a break between two lines of its cells, as Word breaks it; a row with a picture or a merged cell goes to the next page whole |
| a paragraph of the Caption style | in the font of the Caption style, where the DOCX puts it; under a table with only the space before of its style, above one with only its space after |
| an empty paragraph, one of line breaks only, a line break at the start or the end of a paragraph | an empty line, and one more for each line break, as Word shows them |
a page break, a section on a new page, <w:pageBreakBefore> |
a new page |
<w:pgSz> and <w:pgMar> of each later section |
its pages in that size and with those margins, landscape among them |
| no header and no footer in any section | no page number, as Word prints none |
a table of contents field (TOC \o) |
LaTeX's table of contents of its depth, with dot leaders, as Word fills the field, and the empty line Word leaves after it |
a list of figures or tables (TOC \f, TOC \c) |
its entries, with the page LaTeX sets each caption on |
| an equation (OMML) | in Cambria Math, when the container has it; an equation of its own paragraph as a centred line, without the empty line and the space TeX puts around a display |
an upright or bold italic letter of an equation (m:sty p, bi), a colored operator |
upright, bold italic, and an operator with its space, as Word sets them |
a comment (<w:commentReference>) |
a balloon "Commented [n]:" with its text in a grey area right of the text, with a dashed line from the commented text, on a page shrunk to make room for it, as Word for Mac prints it |
The image has no Microsoft fonts. It has open fonts which set text as wide and as high as these fonts of Word, so a line and a page break where Word breaks them:
| Font of Word | Font of the image |
|---|---|
| Aptos, Aptos Display | Metric Sans, Metric Sans Display: Archivo |
| Segoe UI | Metric UI: Selawik, its italics slanted |
| Georgia | Metric Serif: Gelasio |
| Calibri | Carlito |
| Arial, Times New Roman, Courier New | Liberation Sans, Serif, Mono |
The Metric fonts take the outlines of the open font and the width of each character and the line metrics
of the font of Word. fonts/metric_fonts.py makes them in the image build, under
the SIL Open Font License of each open font; the licenses are in /usr/local/share/fonts/metric. A
document in another font the container lacks keeps Latin Modern. Mount the fonts of Word into
/usr/share/fonts to use them instead:
docker run --detach --publish 9082:9082 --volume /path/to/fonts:/usr/share/fonts/truetype/custom:ro \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
The corpus in corpus/ holds the documents of the docx-exporter system tests with
the PDFs Word prints from them. tools/corpus converts them and measures, line by line, how close each
PDF gets to Word's.
External resources of a document
A document names its own resources: an image, a stylesheet, a font. The writers which embed media fetch what it names, so a document reaching this service can ask it to read an address on the network or a path inside its container, and the answer lands in the converted result.
The service therefore runs pandoc sandboxed, and does so by default. Sandboxed, pandoc reads nothing
a document names: no host of the network it sits in, no file of the container. What still works is
everything the conversion itself needs, verified against this image: the lua filters, --reference-doc
templates, the tectonic PDF engine, and images carried inside the document as data: URIs, which is
how docx-exporter sends them.
Because --reference-doc reads its path outside that sandbox, no request gets to name that path. The
service passes the template it wrote from the upload to pandoc as an argument of its own, and the
options form field of the two -with-template endpoints accepts only literal entries of the pandoc
option allowlist, so no accepted option carries a value a request chose.
A PDF is produced by handing the generated LaTeX to tectonic, which runs outside that sandbox and
resolves what the TeX names. These routes reach it, and every one of them is closed on the pdf and
latex targets:
| Route | What is done |
|---|---|
raw TeX, \input{/etc/passwd} as a raw block or inline |
dropped before the LaTeX writer |
the same primitive inside math, $\input{...}$, which the writer emits verbatim |
that formula is dropped, every other one renders as before |
an image the document points at by address, which becomes \includegraphics{...} |
dropped, whatever the source format |
| TeX in the name of a DOCX character style, which the colour filters build raw LaTeX from | only six hex digits are written out, the rest of the name is dropped |
Math is the one thing the writer emits verbatim, so it is held to a rule rather than to a list of the spellings which have been thought of. A formula is dropped when it does any of three things, and what is left cannot reach a file:
| A formula may not | Why |
|---|---|
name a primitive which reads, writes or runs something: \input, \openin, \write, \font, \usepackage, \includegraphics and the rest |
these are what resolve a path |
build a name, alias one, or read a character as another: \csname, \expandafter, \scantokens, \def, \let, \catcode, and the ^^ notation TeX reads as a character |
a formula which cannot make a name cannot reach a primitive the first rule does not list |
carry @, which is a letter only under \makeatletter |
that is how the LaTeX kernel keeps its own names, \@@input among them, away from a document |
The @ rule costs the commutative diagrams of amsmath, which spell their arrows @>>>. Every other
formula renders as before, verified against this image: fractions, greek letters, sums, integrals,
matrices, aligned, and text inside math.
What the DOCX filters of this service emit afterwards is untouched, so the colors, lists and tables of
a DOCX export are unaffected. An image is kept when it travels inside the document: a data: URI, or
media pandoc extracted itself, which is what it asks its media bag rather than the source format, so
an EPUB naming an address of its own is covered like a markdown source is. A document which needs its
own TeX macros, or which points at an image by address, loses them in the PDF.
| Variable | Default | Purpose |
|---|---|---|
PANDOC_SANDBOX |
true |
Run pandoc with --sandbox. Set it to false to let a document load its own resources again. |
Turning it off restores the reach of a document into the network and the file system of the container, so it belongs to a deployment where every caller is trusted and remote images are needed.
HTTPS
Both servers speak plain HTTP by default, which is what a deployment behind a reverse proxy or an ingress expects: TLS terminates there and nothing has to be configured here. That remains the recommended setup where such a component is already in place.
Where the service is reached directly across a network, each server can serve TLS itself.
The API server:
| Variable | Purpose |
|---|---|
TLS_CERT_FILE |
Certificate chain in PEM format |
TLS_KEY_FILE |
Private key in PEM format |
TLS_KEY_PASSWORD |
Password of the key, where it has one |
TLS_CLIENT_CA_FILE |
CA that client certificates are verified against |
TLS_CLIENT_AUTH |
none (default), optional or required |
The metrics server, configured on its own:
| Variable | Purpose |
|---|---|
METRICS_TLS_CERT_FILE |
Certificate chain in PEM format |
METRICS_TLS_KEY_FILE |
Private key in PEM format |
METRICS_TLS_KEY_PASSWORD |
Password of the key, where it has one |
METRICS_TLS_CLIENT_CA_FILE |
CA that client certificates are verified against |
METRICS_TLS_CLIENT_AUTH |
none (default), optional or required |
The two sets are independent and neither inherits from the other. The metrics port can stay plain behind a network rule while the API serves TLS, or the other way round.
docker run --init --detach \
--publish 9082:9082 \
--name pandoc-service \
--volume /path/to/tls:/opt/pandoc/tls:ro \
--env TLS_CERT_FILE=/opt/pandoc/tls/server.pem \
--env TLS_KEY_FILE=/opt/pandoc/tls/server.key \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
An incomplete configuration stops the start with a message naming the variable. The service never falls back to plain HTTP, because serving in the clear while an operator believes otherwise is worse than not starting.
The material is loaded before either server listens, so a key which does not match its certificate, a wrong TLS_KEY_PASSWORD or an unusable CA also stop the start, rather than surfacing at the first connection.
Mutual TLS. With TLS_CLIENT_AUTH=required the service accepts only clients presenting a certificate signed by TLS_CLIENT_CA_FILE. That authenticates the caller, which the API key below does not: the certificate says who connected, the key says who may convert. The two combine.
The healthcheck of the container follows the configured scheme. It talks to its own process over loopback, so it does not verify the certificate. Where client certificates are required, give the probe one with TLS_HEALTHCHECK_CERT_FILE and TLS_HEALTHCHECK_KEY_FILE, otherwise the container reports itself unhealthy. The two go together: one without the other fails the probe with a message naming them, rather than an opaque handshake error.
Certificate renewal. The certificate is read once, at startup. A renewed certificate takes effect when the container restarts.
Prometheus. Once the metrics port serves TLS, its scrape configuration needs scheme: https next to the target.
API key authentication
The conversion and template endpoints can be protected with an API key. The feature is optional and disabled by default.
Configuration:
API_KEY: One or more API keys. Authentication is disabled when the variable is unset or empty.- Several keys are configured as a comma-separated list, for example
API_KEY=key-a,key-b. This allows key rotation without downtime.
Protected endpoints:
| Method | Path |
|---|---|
POST |
/convert/{source_format}/to/{target_format} |
POST |
/convert/{source_format}/to/docx-with-template |
POST |
/convert/{source_format}/to/pptx-with-template |
GET |
/docx-template |
GET |
/pptx-template |
Each of them spawns a pandoc process. /health, /version, /static and /api/docs stay open, so the Docker healthcheck and the published schema keep working. The Prometheus endpoint on port 9182 is not affected; isolate it at the network level.
Start the service with authentication:
docker run --init --detach \
--publish 9082:9082 \
--publish 9182:9182 \
--name pandoc-service \
--env API_KEY=your-secret-key \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
Send the key in the X-API-Key header:
export API_KEY=your-secret-key
curl -X POST -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/html" \
--data @input_html http://localhost:9082/convert/html/to/docx --output output.docx
Or as a bearer token:
curl -X POST -H "Authorization: Bearer ${API_KEY}" -H "Content-Type: application/html" \
--data @input_html http://localhost:9082/convert/html/to/docx --output output.docx
A missing or invalid key answers 401 Unauthorized in plain text, with the header WWW-Authenticate: Bearer. The key value is never written to the log.
The check runs in a middleware, ahead of the request size check. An unauthenticated upload is therefore rejected before its body is buffered, so it costs no memory.
Using as a Base Image
To extend or customize the service, use it as a base image in the Dockerfile:
FROM ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
Prometheus & Grafana Integration
The service exposes Prometheus-compatible metrics for comprehensive monitoring and observability through Grafana dashboards.
Metrics Endpoint: /metrics on port 9182 (dedicated metrics port)
Security: The metrics endpoint is served on a separate port (9182) from the main API (9082). This allows network-level isolation using security groups or firewall rules to restrict metrics access to your Prometheus server only.
Available Metrics:
Conversion Metrics:
pandoc_conversions_total- Total successful conversions (labeled by source/target format)pandoc_conversion_failures_total- Total failed conversions (labeled by source/target format)pandoc_conversion_error_rate_percent- Conversion error rate as percentagepandoc_template_conversions_total- Total conversions using custom templates
Performance Metrics:
pandoc_conversion_duration_seconds- Conversion time histogram (labeled by format)pandoc_subprocess_duration_seconds- Pandoc subprocess execution time histogrampandoc_post_processing_duration_seconds- DOCX/PPTX post-processing time histogramavg_pandoc_conversion_time_seconds- Average conversion time
Size Metrics:
pandoc_request_body_bytes- Input document size histogrampandoc_response_body_bytes- Output document size histogram
Service Metrics:
uptime_seconds- Service uptimeactive_conversions- Current active conversion countpandoc_info- Service and pandoc version information
SVG Metrics (the PNG weasysvg draws):
svg_conversions_total- Total successful SVG→PNG conversionssvg_conversion_failures_total- Total failed SVG→PNG conversionssvg_conversion_duration_seconds- SVG→PNG conversion time histogram
HTTP Metrics (via prometheus-fastapi-instrumentator):
http_request_duration_seconds- HTTP request duration histogramhttp_requests_inprogress- Current in-flight requestshttp_requests_total- Total HTTP requests
Prometheus Configuration Example:
scrape_configs:
- job_name: 'pandoc-service'
static_configs:
- targets: ['pandoc-service:9182'] # Metrics on dedicated port
metrics_path: '/metrics'
scrape_interval: 15s
scrape_timeout: 10s
Grafana Dashboard Queries:
# Conversion rate (requests per second)
rate(pandoc_conversions_total[5m])
# Error rate percentage
sum(rate(pandoc_conversion_failures_total[5m])) / sum(rate(pandoc_conversions_total[5m])) * 100
# 95th percentile conversion duration
histogram_quantile(0.95, rate(pandoc_conversion_duration_seconds_bucket[5m]))
# Conversions by format
sum by (source_format, target_format) (pandoc_conversions_total)
Docker Compose Example with Prometheus & Grafana:
services:
pandoc-service:
image: ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
init: true
ports:
- "9082:9082" # Main API
- "9182:9182" # Metrics endpoint
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus-data:/prometheus
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
volumes:
- grafana-data:/var/lib/grafana
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
prometheus-data:
grafana-data:
Pre-configured Monitoring Stack:
For a complete, production-ready monitoring setup with pre-configured Prometheus, Grafana, and dashboards:
cd monitoring
./start-monitoring.sh
This will start the Pandoc service, Prometheus, and Grafana with a pre-built dashboard. Access Grafana at http://localhost:3000 (admin/admin) and view the dashboard at http://localhost:3000/d/pandoc-service.
For detailed setup instructions and configuration options, see monitoring/README.md.
Development
Building the Docker Image
To build the Docker image from the source with a custom version, use:
docker build \
--build-arg APP_IMAGE_VERSION=0.0.0 \
--file Dockerfile \
--tag pandoc-service:0.0.0 .
Replace 0.0.0 with the desired version number.
Running the Development Container
To start the Docker container with your custom-built image:
docker run --init --detach \
--publish 9082:9082 \
--publish 9182:9182 \
--name pandoc-service \
pandoc-service:0.0.0
Stopping the Container
To stop the running container, execute:
docker container stop pandoc-service
The command sends SIGTERM, which the service handles gracefully. See Graceful Shutdown.
Graceful Shutdown
The service shuts down on SIGTERM, the signal docker stop and Kubernetes send. The signal reaches the service process directly, which then:
- Stops accepting new requests.
- Waits for the running conversions to finish.
- Closes the metrics server.
- Exits with code 143 (128 + SIGTERM), the normal result of a stop by signal.
The wait for running conversions is bounded by the GRACEFUL_SHUTDOWN_TIMEOUT environment variable:
docker run --init --detach \
--publish 9082:9082 \
--name pandoc-service \
--env GRACEFUL_SHUTDOWN_TIMEOUT=60 \
ghcr.io/schweizerischebundesbahnen/pandoc-service:latest
Valid range: 1 - 300 seconds (default: 30). Invalid values fall back to the default with a warning logged.
The conversion runs in a worker thread, so SIGTERM is acted on the moment it arrives and the timeout starts counting at once, whatever a conversion is doing. When the timeout expires the request is dropped and the shutdown finishes, but the worker thread is not interrupted: the pandoc process runs to its end and the service leaves once it returns. Size the stop grace period for the longest document the service converts, not only for the timeout.
MAX_CONCURRENT_PANDOC_CONVERSIONS bounds how many conversions run at the same time (1 - 100, default: 2). Each one holds a worker thread and a pandoc process, and a PDF target adds a tectonic run on top, so raise the limit together with the CPU and the memory of the container.
PANDOC_MAX_HEAP bounds the heap of each pandoc process, in the form of +RTS -M: 2g, 512m, or 0 for no limit. A conversion beyond it stops with 413 Request Entity Too Large instead of growing until the kernel kills it, or kills another process of the container. The limit holds the Haskell heap of pandoc, where a conversion keeps its document, but not what the Lua filters and the C libraries of pandoc allocate, so it is no hard bound on the memory of the container. Unset, the memory limit of the container less 1 GB for the service, weasysvg and tectonic, and at least half of it, is shared between the conversions MAX_CONCURRENT_PANDOC_CONVERSIONS allows. The 1 GB also leaves room for what the filters allocate outside the heap. With two conversions, --memory 8g gives each pandoc 3584 MB and --memory 2g 512 MB. A container without a memory limit gets no heap limit. The limit is read from the cgroup of the container, which is where Docker and Kubernetes put the memory limit of a container. A limit set only on a parent, such as a pod-level limit, is hidden from the container, so state PANDOC_MAX_HEAP there. The log names the limit at startup.
Keep the stop grace period of the orchestrator above GRACEFUL_SHUTDOWN_TIMEOUT (docker stop --time, or terminationGracePeriodSeconds in Kubernetes). A shorter one ends in SIGKILL, which ends the running conversions.
The log line Service shutdown complete marks a shutdown which ran to the end.
The messages uvicorn writes itself (startup, shutdown, errors) use the format of the service log and the same log file, under the uvicorn.error logger name. Per-request access lines are written at DEBUG level only: the Docker healthcheck and the Prometheus scrapes would bury everything else.
Testing
The project includes several test methods to ensure functionality.
Container Structure Test
container-structure-test test --image pandoc-service:local --config ./tests/container/container-structure-test.yaml
Docker Image Smoke Test
To test the Docker image build and API functionality:
bash tests/shell/test_pandoc_service.sh
This script builds the image, starts a container, and performs tests on all endpoints.
Python Tests
# Prepare testing
uv sync --group dev --group test
# Run all Python tests
uv run pytest -v
# Run a specific test
uv run pytest tests/test_docx_post_process.py -v
Tox
# Run all test pytest and linting
uv run tox
Pre-commit
uv run pre-commit run --all
For more detailed testing information, see the tests README.
Access service
Pandoc Service provides the following endpoints:
Getting version info
GET /version
Responses
HTTP code Content-Type Response 200application/json{ "python": "3.15.1", "timestamp": "2024-09-23T12:23:09Z", "pandoc": "3.6.2", "pandocService": "0.0.0", "svgRenderer": "weasysvg", "weasysvg": "0.6.0", "weasyprint": "70.0" }
Example cURL
curl -X GET -H "Content-Type: application/json" http://localhost:9082/version
Getting openapi info
GET /static/openapi.json
Responses
HTTP code Content-Type Response 200application/jsonopenapi.json
Example cURL
curl -X GET -H "Content-Type: application/json" http://localhost:9082/static/openapi.json
Getting docx template
GET /docx-template
Responses
HTTP code Content-Type Response 200application/vnd.openxmlformats-officedocument.wordprocessingml.documentbinary document content
Example cURL
curl -X GET -H "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document" http://localhost:9082/docx-template
Convert HTML to DOCX
POST /convert/html/to/docx
Parameters
Parameter name Type Data type Description encoding optional string Encoding of provided HTML (default: utf-8) file_name optional string Output filename (default: converted-document.pdf) paper_size optional string Paper size for the output document. Supported values: A5, A4, A3, B5, B4, JIS_B5, JIS_B4, LETTER, LEGAL, LEDGER orientation optional string Page orientation. Supported values: portrait, landscape preserve_table_styles optional boolean Preserve CSS table cell styles (background-color, borders, vertical-align) in the DOCX output (default: false)
Responses
HTTP code Content-Type Response 200application/vnd.openxmlformats-officedocument.wordprocessingml.documentDOCX document (binary data) 400plain/textError message with exception 500plain/textError message with exception
Example cURL
curl -X POST -H "Content-Type: application/html" --data @input_html http://localhost:9082/convert/html/to/docx --output output.docxWith custom paper size and orientation:
curl -X POST -H "Content-Type: application/html" --data @input_html "http://localhost:9082/convert/html/to/docx?paper_size=A4&orientation=landscape" --output output.docxWith preserved table styles (background colors, borders):
curl -X POST -H "Content-Type: application/html" --data @input_html "http://localhost:9082/convert/html/to/docx?preserve_table_styles=true" --output output.docx
Convert HTML to DOCX with custom template
POST /convert/html/to/docx-with-template
Parameters
Parameter name Type Data type Description source required file Source HTML content as multipart/form-data template optional file Custom DOCX template file as multipart/form-data encoding optional string Encoding of provided HTML (default: utf-8) file_name optional string Output filename (default: converted-document.docx) paper_size optional string Paper size for the output document. Supported values: A5, A4, A3, B5, B4, JIS_B5, JIS_B4, LETTER, LEGAL, LEDGER orientation optional string Page orientation. Supported values: portrait, landscape preserve_table_styles optional boolean Preserve CSS table cell styles (background-color, borders, vertical-align) in the DOCX output (default: false)
Responses
HTTP code Content-Type Response 200application/vnd.openxmlformats-officedocument.wordprocessingml.documentDOCX document (binary data) 400plain/textError message with exception 500plain/textError message with exception
Example cURL
curl -X POST -F "source=@input.html" -F "template=@custom-template.docx" http://localhost:9082/convert/html/to/docx-with-template --output output.docxWith custom paper size and orientation:
curl -X POST -F "source=@input.html" -F "template=@custom-template.docx" "http://localhost:9082/convert/html/to/docx-with-template?paper_size=A4&orientation=landscape" --output output.docxWith preserved table styles:
curl -X POST -F "source=@input.html" -F "template=@custom-template.docx" "http://localhost:9082/convert/html/to/docx-with-template?preserve_table_styles=true" --output output.docx
Getting pptx template
GET /pptx-template
Responses
HTTP code Content-Type Response 200application/vnd.openxmlformats-officedocument.presentationml.presentationbinary presentation content
Example cURL
curl -X GET http://localhost:9082/pptx-template --output reference.pptx
Convert to PPTX with custom template
POST /convert/{source_format}/to/pptx-with-template
Parameters
Parameter name Type Data type Description source required file Source content as multipart/form-data template optional file Custom PPTX template file as multipart/form-data encoding optional string Encoding of provided source content (default: utf-8) file_name optional string Output filename (default: converted-document.pptx) slide_size optional string Slide size for the presentation. Supported values: 16:9, WIDESCREEN, 4:3, A3, A4, LETTER, LEDGER
Responses
HTTP code Content-Type Response 200application/vnd.openxmlformats-officedocument.presentationml.presentationPPTX presentation (binary) 400plain/textError message with exception 500plain/textError message with exception
Example cURL
curl -X POST -F "source=@input.html" http://localhost:9082/convert/html/to/pptx-with-template --output output.pptxWith custom template:
curl -X POST -F "source=@input.md" -F "template=@custom-template.pptx" http://localhost:9082/convert/markdown/to/pptx-with-template --output output.pptxWith custom slide size:
curl -X POST -F "source=@input.html" "http://localhost:9082/convert/html/to/pptx-with-template?slide_size=16:9" --output output.pptxWith both template and slide size:
curl -X POST -F "source=@input.md" -F "template=@custom-template.pptx" "http://localhost:9082/convert/markdown/to/pptx-with-template?slide_size=4:3" --output output.pptx
Supported Special Variables
The document processor recognizes several special placeholder variables that can be automatically replaced with dynamic Word fields during HTML to DOCX conversion:
Table of Contents Placeholders
- TOC_PLACEHOLDER - Automatically replaced with a Word Table of Contents (TOC) field that lists all headings in your document
- TOF_PLACEHOLDER - Automatically replaced with a Word Table of Figures (TOF) field that lists all figure captions
- TOT_PLACEHOLDER - Automatically replaced with a Word Table of Tables (TOT) field that lists all table captions