Documents On a server: DOCX and PDF
On a server: DOCX and PDF
@rebodocs/core has no DOM and uses no API of Node. The code that lays a document out in the browser runs on your server, so a document made there breaks its lines and pages where the editor would, given the same fonts.
A template, filled and rendered
What a server does, run in this page with the same calls: the template filled with the JSON, its row repeated for each line, laid out with font files read by readFont, and drawn as a PDF. No browser API takes part in it.
Reading the fonts…
Have the template ask for Arial, which the page does not give: missingFonts says so, and the text is set in the font it has. Give the Arial of your machine, and it is set in Arial. The fonts decide where lines and pages break, so the pages a server makes are those of the editor when both have the same ones.
Where it runs
Wherever JavaScript does: the package needs the language and Intl, and takes files as bytes, Uint8Array, whatever read them.
Any version still supported; it is tested on 22. Read templates and fonts with fs, once, when the server starts.
The same package, from npm.
Cloudflare Workers, Vercel and Netlify Edge: there is no disk, so templates and fonts come as bytes, bundled or fetched.
As on this page: the demo above makes its PDF without a server.
A route that makes a PDF
The data comes in as JSON, the document goes out as a PDF, or as a DOCX to be edited. The template and the fonts are read once.
import express from 'express';
import { readFileSync } from 'node:fs';
import { fillVariables, importDocx, readFonts, renderPdf } from '@rebodocs/core';
// Read once, when the server starts. A Doc is never changed in place,
// so one template serves every request at the same time.
const template = importDocx(new Uint8Array(readFileSync('templates/receipt.docx')));
const fonts = ['Arial.ttf', 'Arial Bold.ttf', 'Arial Italic.ttf', 'Arial Bold Italic.ttf']
.flatMap((file) => readFonts(new Uint8Array(readFileSync(`fonts/${file}`))));
const app = express();
app.post('/receipts', express.json(), (req, res) => {
const doc = fillVariables(template, req.body, { locale: 'en-US' });
const { pdf, missingFonts } = renderPdf(doc, fonts, `Receipt ${req.body.number}`);
if (missingFonts.size) console.warn('Stood in for:', missingFonts);
res.type('application/pdf')
.set('Content-Disposition', `attachment; filename="receipt-${req.body.number}.pdf"`)
.send(Buffer.from(pdf));
});// app/receipts/route.ts — the same in Next.js, and with Request and Response
// as they are, in Deno, Bun or a Worker (where the files come by fetch).
import { readFile } from 'node:fs/promises';
import { exportDocx, fillVariables, importDocx, readFonts, renderPdf } from '@rebodocs/core';
const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const ready = (async () => ({
template: importDocx(new Uint8Array(await readFile('templates/receipt.docx'))),
fonts: (await Promise.all(['Arial.ttf', 'Arial Bold.ttf'].map((file) => readFile(`fonts/${file}`))))
.flatMap((bytes) => readFonts(new Uint8Array(bytes))),
}))();
export async function POST(request: Request) {
const { template, fonts } = await ready;
const doc = fillVariables(template, await request.json());
if (new URL(request.url).searchParams.get('as') === 'docx') {
return new Response(exportDocx(doc), { headers: { 'Content-Type': DOCX } });
}
const { pdf } = renderPdf(doc, fonts, 'Receipt');
return new Response(pdf, { headers: { 'Content-Type': 'application/pdf' } });
}The data is the JSON your application already has: nested objects fill {{client.name}}, a list repeats a block, true or false keeps one or takes it out. How to write them is on the page Templates and variables.
Open, change, save
A Doc is an immutable value: every operation returns a new one and leaves the old one as it was. A position is { para, offset }, the paragraph and the character in it.
import { importDocx, exportDocx, insertText, fillVariables } from '@rebodocs/core';
let doc = importDocx(bytes); // Uint8Array → Doc
doc = fillVariables(doc, { client: { name: 'Ana Pérez' }, lines: [{ item: 'Desk', price: 250 }] });
doc = insertText(doc, { para: 0, offset: 0 }, 'DRAFT · ').doc;
const out = exportDocx(doc); // Doc → Uint8Array- importDocx(bytes, { maxSize? }) → Doc
- A DOCX as a document. What the engine does not understand is kept, to be written back as it was. It throws for a file that is not a DOCX, and for one that says it takes more than maxSize unpacked (256 MB when not given).
- fillVariables(doc, data, { locale?, currency?, today? }) → Doc
- The {{variables}} of a template filled, with their formats (upper, currency, long date…), and its blocks written out: {{#lines}} … {{/lines}} once for each item of a list, kept or taken out for true or false. data is the JSON your application has, nested objects and all. locale writes values in a language ('es-MX': 21 de octubre de 2026); without it, in the language of the document, or in English when it says none.
- exportDocx(doc) → Uint8Array
- The document as a DOCX. One opened and saved untouched comes out with the same XML.
- readFont(bytes) → FontFile | undefined
- A .ttf or .otf file, read for its family, weight and widths; of a collection (.ttc), its first face. Undefined for one that is not a font it reads.
- readFonts(bytes) → FontFile[]
- Every face of a file: each of a collection, as macOS keeps Helvetica, made a font of its own.
- renderPdf(doc, fonts, title?, language?) → { pdf, layout, missingFonts, missingPictures }
- The document laid out with those fonts and drawn as a tagged PDF: the layout it used, the families it had to stand in for, and how many pictures it could not draw. The language (es-MX) is the one the file says when not given.
- exportMarkdown(doc, { changes? }) → string
- Headings, emphasis, lists, links and tables as Markdown. No fonts, colours or pictures: for a language model, or an index. Tracked changes come accepted; or as before them (original), or marked [-taken out-]{+put in+} (marked).
- layoutDocument(doc, measurer) → Layout
- Pages and lines, without drawing them. The measurer is anything that tells the width of a text and the height of a font.
Finding where to edit
Positions are not typed by hand: they come from the text. findAll gives the range of each place a text is, and paragraphText the text of a paragraph; a table’s paragraphs are among the others, each with the cell it is in.
import { findAll, replaceAll, paragraphText, insertText } from '@rebodocs/core';
const [where] = findAll(doc, 'Payment is due'); // [{ from: { para, offset }, to }]
doc = insertText(doc, where.to, ' in full').doc; // after what was found
doc = replaceAll(doc, '15 days', '30 days', { wholeWord: true }).doc;
const title = doc.paragraphs.findIndex((p) => paragraphText(p).startsWith('Annex'));Everything else it does
What the editor does to a document, the core does without one: every button of the editor is one of these calls. Each takes a document and gives back a new one.
insertTextdeleteRangesplitParagraphfindAllreplaceAllreplaceRangetextInRangedocText
applyRunPropssetParagraphPropssetParagraphStyletoggleListsetListStylerestartNumbering
insertTableinsertRowdeleteRowinsertColumnmergeCellssetCellPropssetHeaderRowinsertSignatures
insertImageinsertImageGridresizePicturesetPictureWrapimageTypeOf
setSectionPageinsertSectionBreaksetColumnssetPageNumberingsetOwnFirstPagesetEndnotesAtsetNoteNumbering
insertLinksetLinkinsertTocupdateTocinsertFootnoteinsertEndnote
revisionsOfacceptRevisionsrejectRevisionsdecideAllRevisionsaddNoteremoveNoteremoveAllNotes
compareDocsdescribeChangerestoreVersion
setLetterheadremoveLetterheadpngLetterheadMarginswithLetterheadMargins
variableNamestemplateBlocksfillVariablesvariableProblemsformatValue
The comments in the source say what each takes and gives: the file to open is the module named. The editor’s own methods, which call these, are on the page Editor API.
Laying out needs to know how wide text is. In the browser that is asked of the browser; on a server it is read from font files.
import { readFileSync } from 'node:fs';
import { importDocx, readFonts, renderPdf } from '@rebodocs/core';
const fonts = ['Arial.ttf', 'Arial Bold.ttf', 'Arial Italic.ttf']
.flatMap((file) => readFonts(new Uint8Array(readFileSync(`fonts/${file}`))));
const { pdf, layout, missingFonts, missingPictures } = renderPdf(importDocx(bytes), fonts, 'Receipt 1024');
layout.pages.length; // how many pages it made
missingFonts; // e.g. Map { 'Calibri' => 'Arial' }: give the real one for the same lines
missingPictures; // pictures of a kind it does not draw, left outTrueType ones cut down to the characters used; OpenType ones in CFF whole. The text can be selected and searched.
Fonts the DOCX carries inside are used by themselves, before the ones you give: they are the ones it was written with.
A family you did not give is set in one of its kind you did (for a sans: Arial, Liberation Sans, Helvetica, DejaVu Sans; for a serif, Times New Roman and its likes; for a mono, Courier New), else in the first you gave, in the face of its style, and named in missingFonts.
A Chinese character the font has not is drawn in the font for Chinese the document names (w:eastAsia), when you give it, or else in the one every PDF reader has: STSong-Light, or MSung-Light for Taiwan and Hong Kong.
PNG of 8 or 16 bits to the sample, GIF (its first frame), and JPEG, which goes in as it is. Any other is left out and counted in missingPictures.
A server has no fonts unless you put them there. Ship the ones your documents use, as the fonts page tells, and read missingFonts to know when one was stood in for.
- The fonts inside it, and text that can be selected, searched and copied.
- Links that open: to an address, and inside the document to its bookmarks, as the entries of a table of contents do.
- Headers, footers, page numbers, notes at the foot of the page and at the end, tables, columns, text boxes and letterheads, where the editor puts them.
- Chinese text, in the font for Chinese of the document or the one every reader has.
- Its title, the one given to renderPdf, and its language.
- Tags for screen readers: headings, lists, tables, notes, links, and pictures with their description. See Accessibility.
- The headings as bookmarks in the side bar of the reader.
- PDF/A for archiving, forms to fill, a password or a signature.
- Author, subject or keywords.
How fast
The receipt of the demo, its block repeated to make longer documents, filled and written on an Apple M1 with Node 22, the fonts already read. The median of seven runs.
| Pages | fillVariables | exportDocx | renderPdf | PDF size |
|---|---|---|---|---|
| 1 | 1 ms | 0.6 ms | 3 ms | 12 KB |
| 6 | 7 ms | 0.9 ms | 17 ms | 25 KB |
| 30 | 26 ms | 3 ms | 77 ms | 81 KB |
It all runs on the thread that calls it: a long document holds that thread for as long as it takes. For many at once, or very long ones, make them in a worker or a queue. Reading the fonts takes longer than a page: keep them read.
Documents sent by others
A DOCX is a zip file, and one made to harm can say it unpacks to far more than it weighs. importDocx adds up what each file of it says it takes before unpacking any, and refuses one past maxSize.
let doc;
try {
doc = importDocx(upload, { maxSize: 50 * 1024 * 1024 }); // 50 MB unpacked at most
} catch (error) {
return new Response(`Not a document we can read: ${(error as Error).message}`, { status: 400 });
}- No macro, script or link in a document is run or followed: what the engine does not understand is kept as XML, to be written back.
- The limit is on what the package says. Give your server a limit of its own too, on the size of what it is sent and the time a request may take.
- Pictures of a document are drawn from its own bytes: nothing is fetched from an address in it.
The command-line tool
The same without writing code. It comes with @rebodocs/mcp, which reads the fonts of the machine; in a clone of the repository, npm run generate -- … runs it from its source.
npx -p @rebodocs/mcp rebodocs-generate template.docx data.json -o receipt.pdf --fonts ./fonts --locale en-US
npx -p @rebodocs/mcp rebodocs-generate template.docx data.json -o receipt.docx
npx -p @rebodocs/mcp rebodocs-generate contract.docx -o contract.md
npx -p @rebodocs/mcp rebodocs-generate template.docx --list- template.docx
- The template.
- data.json
- Its values. Nested objects give dotted names: { "client": { "name": "Ana" } } fills {{client.name}}; a list fills a block, {{#lines}} … {{/lines}}.
- -o out.pdf | out.docx | out.md
- What to make, by its extension.
- --fonts folder
- Where the .ttf, .otf and .ttc files are, for a PDF; more than one may be given. Then those of the system.
- --locale en-US · --currency EUR
- The language dates and numbers are written in, and the currency of currency. Left out, the language of the document (or English) and a dollar sign.
- --list
- Only the names of the variables of the template, one a line, and its blocks.
It warns of the variables and blocks left without a value, and of a value a format cannot take, which is then put as it is.
Laying out yourself
To know how many pages a document has, or where a line falls, without drawing it.
import { FontMeasurer, layoutDocument } from '@rebodocs/core';
const layout = layoutDocument(doc, new FontMeasurer(fonts));
layout.pages.length; // how many pages
layout.lines[0]; // where the first line is, and what is on itlayoutDocument takes anything that can say the width of a text and the height of a font (TextMeasurer), which is how the browser and the server share it: the editor measures with the browser, FontMeasurer with font files.
A typical backend
For an application that fills templates and lets people edit the result:
Keep the templates as DOCX in your storage, and the fonts they use beside your code.
To make one:
importDocx→fillVariables→exportDocx, orrenderPdf, and store the result.To edit it: give the stored DOCX to the React component and store what
onSavehands back. Documents in an S3 bucket does it, with a demo to run.For several people at once, see collaboration.