Showcases

PDF/A invoices from a Word template

Turn a Word template and JSON data into PDF/A-3 documents, one per record, from Python, JavaScript, a web page or Delphi with one JSON-RPC call.

Report Module · Python · JavaScript · Web page · Delphi

The problem

Invoices, delivery notes and certificates must be archived as PDF/A, the ISO format for long-term preservation, and their layout changes often. Generating them inside every application means a PDF library per language and a developer every time the layout changes.

How DMSContainer solves it

The layout is a normal Word document with placeholders such as {{ item.customer }}, so it can be edited by whoever owns it. Your application sends the template and the data as JSON to the Report Module and receives a zip file with one PDF/A-3 document for each item. The same call produces pdf, pdfa2, pdfa3, pdfa4, pdfua, docx or html.

The template

A Word file (invoice.docx) with, for example:

Invoice {{ item.number }}
Customer: {{ item.customer }} - Total: {{ item.total }}

Python

import base64
import requests

URL = "https://dms.example.com/reportsrpc"  # your DMSContainer
USER, PASSWORD = "my_user", "my_password"


def call(method, *params):
    r = requests.post(URL, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": list(params)}).json()
    error = r.get("error") or (r.get("result") or {}).get("error")
    if error:
        raise RuntimeError(error["message"])
    return r["result"]


token = call("Login", USER, PASSWORD)["token"]

# invoice.docx is a normal Word document with {{ item.number }}, {{ item.customer }}, {{ item.total }}
with open("invoice.docx", "rb") as f:
    template = {"template_data": base64.b64encode(f.read()).decode()}

data = {
    "meta": {},
    "items": [  # one document for each item
        {"number": "2026/1024", "customer": "ACME Srl", "total": "1,250.00"},
        {"number": "2026/1025", "customer": "Globex SpA", "total": "380.00"},
    ],
}

result = call("GenerateMultipleReport", token, template, data, "pdfa3")
with open("invoices.zip", "wb") as f:
    f.write(base64.b64decode(result["zipfile"]))  # two PDF/A-3 invoices

JavaScript (Node.js)

// Node.js 18 or later (built-in fetch)
const fs = require("fs");

const URL = "https://dms.example.com/reportsrpc"; // your DMSContainer
const USER = "my_user", PASSWORD = "my_password";

async function call(method, ...params) {
  const response = await fetch(URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  const r = await response.json();
  const error = r.error || (r.result && r.result.error);
  if (error) throw new Error(error.message);
  return r.result;
}

(async () => {
  const { token } = await call("Login", USER, PASSWORD);
  const template = { template_data: fs.readFileSync("invoice.docx").toString("base64") };
  const data = {
    meta: {},
    items: [
      { number: "2026/1024", customer: "ACME Srl", total: "1,250.00" },
      { number: "2026/1025", customer: "Globex SpA", total: "380.00" },
    ],
  };
  const { zipfile } = await call("GenerateMultipleReport", token, template, data, "pdfa3");
  fs.writeFileSync("invoices.zip", Buffer.from(zipfile, "base64"));
})();

JavaScript in a web page

The same call from the browser: the user signs in with their own DMSContainer account (never write credentials in the page) and gets the file as a download. Serve the page over HTTPS.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>PDF/A invoices</title>
<form id="form">
  <input id="user" placeholder="DMSContainer user" autocomplete="username" required>
  <input id="password" type="password" placeholder="Password" autocomplete="current-password" required>
  <input id="template" type="file" accept=".docx" required>
  <button>Create the invoices</button>
</form>
<p id="status"></p>
<script>
const ENDPOINT = "https://dms.example.com/reportsrpc"; // your DMSContainer

async function call(method, ...params) {
  const response = await fetch(ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  const r = await response.json();
  const error = r.error || (r.result && r.result.error);
  if (error) throw new Error(error.message);
  return r.result;
}

// a link that saves the file the service returned (base64)
function downloadLink(base64, fileName, type) {
  const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
  const link = document.createElement("a");
  link.href = URL.createObjectURL(new Blob([bytes], { type }));
  link.download = fileName;
  link.textContent = "Download " + fileName;
  return link;
}
function toBase64(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result.split(",")[1]); // without "data:...;base64,"
    reader.readAsDataURL(file);
  });
}

document.getElementById("form").addEventListener("submit", async (event) => {
  event.preventDefault();
  const status = document.getElementById("status");
  try {
    const { token } = await call("Login", document.getElementById("user").value,
      document.getElementById("password").value);
    const template = { template_data: await toBase64(document.getElementById("template").files[0]) };
    const data = {
      meta: {},
      items: [
        { number: "2026/1024", customer: "ACME Srl", total: "1,250.00" },
        { number: "2026/1025", customer: "Globex SpA", total: "380.00" },
      ],
    };
    const { zipfile } = await call("GenerateMultipleReport", token, template, data, "pdfa3");
    status.replaceChildren(downloadLink(zipfile, "invoices.zip", "application/zip"));
  } catch (error) {
    status.textContent = error.message;
  }
});
</script>
</html>

Delphi

program Invoices;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.IOUtils, System.NetEncoding,
  JsonDataObjects, ReportsRPCProxy; // ReportsRPCProxy.pas: in the samples, or generated by the console

const
  URL = 'https://dms.example.com/reportsrpc'; // your DMSContainer
  USER = 'my_user';
  PASSWORD = 'my_password';

var
  lProxy: IReportsRPCProxy;
  lToken: string;
  lTemplate, lData, lItem, lResult: TJsonObject;
begin
  lProxy := TReportsRPCProxy.Create(URL);
  lResult := lProxy.Login(USER, PASSWORD);
  try
    lToken := lResult.S['token'];
  finally
    lResult.Free;
  end;

  // the proxy owns the objects it sends: do not free lTemplate and lData
  lTemplate := TJsonObject.Create;
  lTemplate.S['template_data'] := TNetEncoding.Base64String.EncodeBytesToString(TFile.ReadAllBytes('invoice.docx'));
  lData := TJsonObject.Create;
  lData.O['meta'];
  lItem := lData.A['items'].AddObject;
  lItem.S['number'] := '2026/1024';
  lItem.S['customer'] := 'ACME Srl';
  lItem.S['total'] := '1,250.00';
  lItem := lData.A['items'].AddObject;
  lItem.S['number'] := '2026/1025';
  lItem.S['customer'] := 'Globex SpA';
  lItem.S['total'] := '380.00';

  lResult := lProxy.GenerateMultipleReport(lToken, lTemplate, lData, 'pdfa3');
  try
    if not lResult.IsNull('error') then
      raise Exception.Create(lResult.O['error'].S['message']);
    TFile.WriteAllBytes('invoices.zip', TNetEncoding.Base64String.DecodeStringToBytes(lResult.S['zipfile']));
  finally
    lResult.Free;
  end;
end.

The result

invoices.zip holds two PDF/A-3 files, one per invoice, ready to be archived or sent. Every snippet on this page is run against a real DMSContainer before it is published.

The Report Module Download the free trial