In short
A chapter of a baking manual shown page by page inside a web page, the way an editing system would show it. Buttons above the pages zoom in and out, fit a page to the window and go to the next or previous page.
What you'll build
The third chapter of Flour, Water, Salt, a baking manual on a 140 × 210 mm page, shown inside a web page the way an editing system shows proofs. The pages run down a dark column, each on its own sheet of white, and a toolbar above them carries the controls an editor reaches for: back and forward, zoom out and in, fit to the width, show a whole page, and a counter that reads "Page 2 of 3". The toolbar belongs to the host. The viewer paints the pages, follows the scroll, and reports each change of page and zoom; the host draws its buttons from those reports.
This recipe answers
- How do I show a laid-out book inside my CMS, with zoom and page navigation?
The short answer
// `view`, not `viewer`: the kit's viewer block declares a function of that name.
const view = createViewer(document.getElementById('viewer'), {
document: doc,
markdown, // the source: copying a selection gives the Markdown, not the painted text
zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
minZoom: 0.4, maxZoom: 3, gap: 24,
labels: labels.viewer, // what a screen reader hears: "Page 3 of 41", the selection's size
});
const $ = (id) => document.getElementById(id);
// The viewer says what changed; the host draws its own controls from that.
const showPage = (i) => {
const folio = doc.pages[i].pageLabel || String(i + 1);
$('counter').textContent = t({ en: `Page ${folio} of ${doc.pages.length}`,
es: `Página ${folio} de ${doc.pages.length}` });
$('prev').disabled = i === 0;
$('next').disabled = i === doc.pages.length - 1;
};
view.on('pagechange', ({ pageIndex }) => showPage(pageIndex));
const showZoom = (zoom) => { $('percent').textContent = `${Math.round(zoom * 100)} %`; };
view.on('zoomchange', ({ zoom }) => showZoom(zoom));
const clicks = {
prev: () => view.goToPage(view.pageIndex - 1),
next: () => view.goToPage(view.pageIndex + 1),
'zoom-out': () => view.setZoom(view.zoom / 1.25), // clamped to minZoom by the viewer
'zoom-in': () => view.setZoom(view.zoom * 1.25),
'fit-width': () => view.setZoom('fit-width'), // a fitted mode follows the container
'fit-page': () => view.setZoom('fit-page'),
};
for (const [id, run] of Object.entries(clicks)) $(id).addEventListener('click', run);
The viewer in the host's container, and a toolbar it keeps up to date
Ingredients
- Features
- Page viewer (postext-viewer)Pages on a canvasFonts before layoutDesigned openersHeading attributesRunning heads and foliosMirrored marginsSemantic colour palette
- Also uses
- Heads by page role
- Type
- Literata, Fraunces, Work Sans (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · Set a page worth looking at closely
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { y: mm(8) } } },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
size: { width: mm(90) } } },
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
A viewer zooms to 300 %, so the page has to hold up under it: a sunk opener with a kicker from the heading's attributes, and running heads that change side with the page. The same config would print; the viewer adds nothing to the layout.
#2 · Open the viewer and listen to it
The code is the short answer above. createViewer fills its container, so the container gets a height, here the window less the toolbar. In its first frame the viewer reports the zoom and the page it opens on, so the toolbar only listens to zoomchange and pagechange. Zoom buttons multiply the current zoom; the viewer clamps it to minZoom and maxZoom and keeps the place in view.
#3 · Name everything in the reader's language
const labels = t({
en: { prev: 'Previous page', next: 'Next page', 'zoom-out': 'Zoom out', 'zoom-in': 'Zoom in',
'fit-width': 'Fit width', 'fit-page': 'Whole page', tools: 'Pages',
viewer: {} }, // the viewer speaks English unless told otherwise
es: { prev: 'Página anterior', next: 'Página siguiente', 'zoom-out': 'Reducir',
'zoom-in': 'Ampliar', 'fit-width': 'Ajustar al ancho', 'fit-page': 'Página entera',
tools: 'Páginas',
viewer: { viewer: 'Páginas del libro', page: 'Página {n} de {count}',
selection: '{count} caracteres seleccionados', selectionCleared: 'Selección borrada' } },
});
The viewer names its region and each page for screen readers ("Page 3 of 41") and announces a selection's size. In English it needs nothing; the Spanish edition passes its own labels, and the toolbar's buttons get names of their own because two of them show only an arrow or a sign. The page viewer docs list every label and option.
The whole recipe
// ═══ Postext Cookbook · Nº 211 · A book in a page viewer ══════════════════════════════
// https://postext.dev/en/cookbook/book-in-a-page-viewer
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Literata, Fraunces, Work Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a baking manual, laid out once and shown in postext-viewer as a CMS would show
// it: a scrolling column of pages, zoom buttons, fit to the width or to the page, and a page
// counter. The toolbar is the host's own; the viewer only reports what changed.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'book-in-a-page-viewer';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#1f1c19', // text: a warm near-black
accent: '#8a4b1f', // crust brown: kicker, rule, list numbers, folios
muted: '#6f675e', // running heads
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [OUTER, LEAD] = [15, 14]; // mm from the outer edge to the folios; pt of body leading
// #region book: a manual's page, a sunk chapter opener and running heads by parity
const opener = { enabled: true, minHeight: mm(46), slot: { elements: [
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: 'Work Sans',
fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.5), textTransform: 'uppercase',
color: col('accent'), align: 'left', placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { y: mm(8) } } },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Fraunces', fontSize: pt(26),
lineHeight: 1.05, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(3) },
size: { width: mm(90) } } },
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.25), color: col('accent'),
placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
size: { width: mm(12) } } },
] } };
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
pages: 'body', fontFamily: 'Work Sans', fontSize: pt(7), fontWeight: 500,
letterSpacing: pt(1.1), textTransform: 'uppercase', color: col('muted'),
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(11) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
<main id="pages">
<nav id="tools">
<div class="group">
<button id="prev" type="button">‹</button>
<span id="counter" role="status"></span>
<button id="next" type="button">›</button>
</div>
<div class="group">
<button id="zoom-out" type="button">−</button>
<span id="percent"></span>
<button id="zoom-in" type="button">+</button>
<button id="fit-width" type="button" class="word"></button>
<button id="fit-page" type="button" class="word"></button>
</div>
</nav>
<div id="viewer"></div>
</main>
/* The host's frame: a toolbar over the viewer. The viewer fills its container,
so the container gets a height: whatever the window leaves under the toolbar. */
main#pages {
display: flex; flex-direction: column; height: max(540px, 100vh);
justify-items: normal; padding: 0;
}
#tools {
display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px 24px;
padding: 8px 16px; background: #16181d; border-bottom: 1px solid #23262d;
font: 500 14px/1.2 system-ui, sans-serif; color: #f4f1ea;
}
#tools .group { display: flex; align-items: center; gap: 6px; }
#tools button {
min-width: 44px; min-height: 44px; padding: 0 12px; border: 1px solid #4a505b;
border-radius: 6px; background: #1f2229; color: #f4f1ea; font: inherit; font-size: 18px;
cursor: pointer;
}
#tools button.word { font-size: 14px; }
#tools button:hover:not(:disabled) { border-color: #d8a21a; }
#tools button:disabled { color: #6c7079; cursor: default; }
#tools button:focus-visible { outline: 2px solid #d8a21a; outline-offset: 2px; }
#counter, #percent { min-width: 7.5em; text-align: center; font-variant-numeric: tabular-nums; }
#percent { min-width: 4.5em; }
#viewer { flex: 1; min-height: 0; }
/* The viewer's look: custom properties on its own element (.postext-viewer). */
#viewer .postext-viewer {
--pv-background: #0e1014;
--pv-page-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 18px 40px -16px rgb(0 0 0 / .8);
--pv-focus: #d8a21a;
}
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Open at the width of the column
For proofreading, a page as wide as the window reads better than a whole page.
- zoom: 'fit-page', // a whole page in view; a number is CSS px per page px
+ zoom: 'fit-width', // the page as wide as the container; the column scrolls#Turn the pages in 3D
A laid-out book on the desk opens the same kind of document as a book the reader turns by hand.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- Literata (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Work Sans (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)



