跳到主要内容
食谱编号211

排版食谱 · 第13章 · CMS集成

页面查看器里的书:缩放与翻页

postext-viewer 的 createViewer 把排好的一章显示为 CMS 中的一列页面,缩放按钮和页码计数器则由网站自己提供。

本页内容
难度
中级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
查看器刚打开时:整页 Flour, Water, Salt 显示在宿主应用自己的工具栏下方,工具栏上有页码计数和缩放按钮。
查看器刚打开时:整页 Flour, Water, Salt 显示在宿主应用自己的工具栏下方,工具栏上有页码计数和缩放按钮。
  • 英文样例:尚无中文版本
  • 成品尺寸140 × 210 mm
  • 1栏
  • Literata 9.8/14
  • Fraunces
  • Work Sans
  • 3页
  • 难度
  • Postext 1.103.1
  • 排版用时11 ms
  • 138行代码

简单来说

一本烘焙手册的一章,在网页里一页一页地显示,就像编辑系统里那样。上方的按钮可以放大、缩小、让页面适应窗口,也可以翻到下一页或上一页。

成品一览

烘焙手册 Flour, Water, Salt 的第三章,开本 140 × 210 mm,像编辑系统显示校样那样显示在网页里。页面沿一条深色的栏往下排,每页一张白纸;上方的工具栏放着校对时要用的按钮:上一页和下一页、缩小和放大、适应宽度、整页显示,还有一个显示当前页和总页数的计数器。工具栏属于网站。查看器负责绘制页面、跟随滚动,并报告每次翻页和缩放的变化;网站根据这些报告更新自己的按钮。

这道食谱解答

  • 怎样在我的CMS里显示排好的书,并提供缩放和翻页导航?

简短回答

script.js · 第148–176行在完整代码中
// `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);

用料

类型
Literata, Fraunces, Work Sans(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 排出经得起放大的页面

script.js · 第31–54行在完整代码中
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),
] };

查看器能放大到 300 %,所以页面要经得起细看:开篇位置下沉,眉题取自标题的属性,书眉随奇偶页换边。同样的配置也可以用来印刷;查看器不会改动版面。

#2 · 打开查看器,监听它的事件

代码就是上面的简短回答。createViewer 会填满它的容器,所以容器要有高度,这里是窗口高度减去工具栏。查看器在第一帧就报告打开时的缩放和页码,所以工具栏只需监听 zoomchange 和 pagechange。缩放按钮把当前缩放值相乘;查看器会把它限制在 minZoom 和 maxZoom 之间,并保持原来看到的位置。

#3 · 用读者的语言命名一切

script.js · 第135–144行在完整代码中
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' } },
});

查看器为屏幕阅读器给自己的区域和每一页命名,并读出选区的长度。英文版无需设置;西班牙文版传入自己的 labels。工具栏的按钮也有自己的名称,因为其中两个只显示箭头或符号。页面查看器文档列出了所有标签和选项。

完整食谱

// ═══ 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') };

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#按栏宽打开

校对时,和窗口一样宽的页面比整页显示更好读。

-  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

#以3D翻页

把排好的书放到桌上,以3D呈现 把同类文档打开成一本可以用手翻的书。

致谢

文本
原创文字, CC BY 4.0
字体
Literata (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Work Sans (SIL OFL 1.1)