跳到主要内容
食谱编号106

排版食谱 · 第2章 · 字体与文字

阿拉伯文—英文双语报告

阿拉伯文年度报告,英文译文排在旁边:英文块和标题加{dir=ltr},阿拉伯文句中的拉丁名称用:ltr[…],还有一张从左向右的表格。

本页内容
类型
报告
输出
Canvas · PDF
难度
中级
Postext
已用Postext 1.15.0测试
需要≥ 1.15.0 · postext-pdf ≥ 1.15.0
许可证
更新于2026年10月4日
代码MIT · 文本CC BY 4.0

页码١ · 第1页,共3页

  • 英文样例:尚无中文版本
  • 成品尺寸210 × 280 mm
  • 1栏
  • IBM Plex Sans Arabic 11/18
  • IBM Plex Sans
  • 3页
  • 难度
  • Postext 1.15.0
  • 排版用时17 ms
  • 140行代码

简单来说

一家基金会用阿拉伯文写的年度报告,每段后面跟着英文译文。页面混排两种方向,词语、数字和表格都不会乱序。

成品一览

虚构的翻译基金会“达德之家”2025年年度报告,页面210 × 280 mm,字体是IBM Plex Sans Arabic和IBM Plex Sans,同一字族的两半。报告是阿拉伯文的:从右向左排,页码印作٢、٣。每段阿拉伯文后面跟着它的英文版本,字号较小,石板灰色,从左向右排,右侧不齐;每个阿拉伯文标题在另一侧边距配一个英文标签。阿拉伯文句子里的拉丁名称保持自己的顺序,全年的数字出现两次:一张从右读的阿拉伯文表格,一张从左读的英文表格。西班牙文版中,第二语言是西班牙文。

这道食谱解答

  • 怎样在同一页混排阿拉伯文和英文的段落、数字和表格?

简短回答

script.js · 第32–45行在完整代码中
// The document is Arabic (locale 'ar'): right to left, Arabic-Indic digits. A block in the
// other language says so in the Markdown, and its style gives it its own voice:
//   :::paragraphs{style="second" dir=ltr}      a paragraph or several, set left to right
//   ### Director's note {style="second-head" dir=ltr}
// Inside an Arabic sentence, a Latin name is an isolate, :ltr[Penguin Classics]{lang=en}, so
// the words around it keep their order. 'start' and 'end' follow each block's own direction.
const second = { id: 'second', fontFamily: LATIN, fontSize: pt(9.5), lineHeight: pt(14),
  color: col('slate'), textAlign: 'start', firstLineIndent: pt(0) };
const bodyText = { fontFamily: ARABIC, fontSize: pt(11), lineHeight: pt(LEAD),
  color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'start', // ragged: the right edge for Arabic, the left for an English block
  firstLineIndent: pt(0), paragraphSpacing: true,
  // The Arabic is never slanted; italics stay for the titles in the Latin blocks.
  emphasis: 'italic' };

用料

类型
IBM Plex Sans Arabic, IBM Plex Sans(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 用标记的块排第二语言

代码见上文的简短回答。文档是阿拉伯文,所以除非Markdown另有说明,每个块都从右向左:在:::paragraphs围栏或标题上加{dir=ltr},就把那个块翻转过来,textAlign: 'start'让每个块靠向它开始的一侧,阿拉伯文靠右,英文靠左(文档、块与行内方向)。阿拉伯文行内的拉丁名称:ltr[Harbour Modern Classics]是一个隔离段:双向算法把它当作一个中性整体,周围的阿拉伯文词语和逗号位置不变(隔离段)。emphasis: 'italic'让英文中的Middlemarch保持斜体;无论怎样设置,引擎都不会把阿拉伯字母排成斜体。

#2 · 每个方向一张表

script.js · 第49–82行在完整代码中
const cell = (content, extra = {}) => ({ content, ...extra });
const tableOf = (head, rows) => ({ headerRowCount: 1, columnWidths: [46, 18, 18, 18],
  rows: [head.map((h, i) => cell(h, { isHeader: true, align: i ? 'end' : 'start' })),
    ...rows.map((r) => r.map((c, i) => cell(c, { align: i ? 'end' : 'start' })))] });
const FIGURES = [ // programme, 2024, 2025, change: the Foundation's own counts
  ['كتب مترجمة إلى العربية', 'Books translated into Arabic', 28, 34],
  ['كتب مترجمة من العربية', 'Books translated from Arabic', 9, 14],
  ['منح للمترجمين', 'Translator grants', 41, 52],
  ['ورشات تدريب', 'Training workshops', 12, 18],
  ['مشاركون في الورشات', 'Workshop participants', 310, 466]];
const SPANISH = { 'Books translated into Arabic': 'Libros traducidos al árabe',
  'Books translated from Arabic': 'Libros traducidos del árabe',
  'Translator grants': 'Becas para traductores', 'Training workshops': 'Talleres de formación',
  'Workshop participants': 'Participantes en los talleres' };
const change = (a, b) => `${b > a ? '+' : ''}${Math.round((100 * (b - a)) / a)}%`;
const AR = (n) => String(n).replace(/\d/g, (d) => '٠١٢٣٤٥٦٧٨٩'[d]); // the author's ٠–٩
const tableAr = tableOf(['البرنامج', '٢٠٢٤', '٢٠٢٥', 'التغيّر'], FIGURES.map(([ar, , a, b]) =>
  [ar, AR(a), AR(b), AR(change(a, b)).replace('%', '٪')]));
const tableEn = tableOf(t({ en: ['Programme', '2024', '2025', 'Change'],
  es: ['Programa', '2024', '2025', 'Cambio'] }), FIGURES.map(([, en, a, b]) =>
  [t({ en, es: SPANISH[en] }), String(a), String(b), change(a, b)]));
// The English table has a heading of its own and no number: a generated number would print in
// the document's digits, ٢, inside the English block.
const resourceTypes = [...defaultResourceTypes('ar'), { id: 'data', name: 'Data',
  shortLabel: 'Data', captionPrefix: '', numberingTemplate: '', resetOn: 'never',
  counterFormat: 'decimal' }];
const resources = [
  { id: 'figures-ar', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tableAr }, placement: { position: 'here' },
    caption: 'أرقام البرامج في عامي ٢٠٢٤ و٢٠٢٥' },
  { id: 'figures-en', typeId: 'data', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tableEn, direction: 'ltr', styleId: 'second' },
    placement: { position: 'here' } },
];

阿拉伯文表格跟随文档方向:第一列“项目”在右边,align: 'end'让数字靠单元格左边。英文表格设了direction: 'ltr',所以第一列在左边,'end'指右边(左、右、起始与末尾的含义)。阿拉伯文数字用٠–٩输入,英文用0–9:文档的数字系统只用于引擎生成的数字,比如图注里的表格编号جدول ١-١。这也是英文表格单独用一个不计数的类型的原因,否则那里的编号会印成٢。

#3 · 一条色带上的两个标题

script.js · 第86–100行在完整代码中
const band = { enabled: true, minHeight: mm(70), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('teal') },
    placement: { anchor: { to: 'bleed', edge: 'top-left' },
      size: { width: mm(216), height: mm(86) } } },
  // Design text takes the document's direction; an English title says 'ltr' and aligns left.
  { kind: 'text', id: 'org', content: '{attr.org}', fontFamily: ARABIC, fontSize: pt(13),
    fontWeight: 600, color: col('tint'), align: 'right',
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-SIDE), y: mm(18) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: ARABIC, fontSize: pt(50),
    fontWeight: 700, lineHeight: 1.15, color: col('paper'), align: 'right',
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-SIDE), y: mm(30) } } },
  { kind: 'text', id: 'title-2', content: '{attr.second}', direction: 'ltr', fontFamily: LATIN,
    fontSize: pt(20), fontWeight: 300, color: col('tint'), align: 'left',
    placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(SIDE), y: mm(66) } } },
] } };

封面是一级标题的设计。设计文字采用文档的方向,所以阿拉伯文名称和标题无需设置;英文标题设direction: 'ltr',锚定在页面左边缘。色带是锚定到出血线的框,深86 mm,章首的minHeight让主任致辞排在它下面。

完整食谱

沙盒
// ═══ Postext Cookbook · Nº 106 · A bilingual Arabic–English report ═══════════════════
// https://postext.dev/en/cookbook/bilingual-arabic-english-report
// Code: MIT · Text: original Arabic, English and Spanish prose (CC BY 4.0) · Pictures: none
// Fonts: IBM Plex Sans Arabic, IBM Plex Sans (SIL OFL 1.1) · Needs postext ≥ 1.15.0
import {
  buildDocument, renderPageToCanvas, clearMeasurementCache, defaultResourceTypes,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the second language of the report: English, or Spanish in 'es'
const RECIPE = 'bilingual-arabic-english-report';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a deep teal for the Arabic, a slate for the second language
const palette = {
  ink: '#1b1f22', // the Arabic text
  teal: '#0e5a5c', // the accent: the cover band, headings, table heads
  slate: '#45535c', // the English (or Spanish) text: a voice of its own, a step lighter
  tint: '#e4eeec', // the second language's panels
  rule: '#b9c4c2', // hairlines
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.teal })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const [ARABIC, LATIN] = ['IBM Plex Sans Arabic', 'IBM Plex Sans']; // one superfamily
const LEAD = 18; // pt: the Arabic leading
const SIDE = 20; // mm: the side margins

// #region answer: one Arabic document, its English blocks marked {dir=ltr}
// The document is Arabic (locale 'ar'): right to left, Arabic-Indic digits. A block in the
// other language says so in the Markdown, and its style gives it its own voice:
//   :::paragraphs{style="second" dir=ltr}      a paragraph or several, set left to right
//   ### Director's note {style="second-head" dir=ltr}
// Inside an Arabic sentence, a Latin name is an isolate, :ltr[Penguin Classics]{lang=en}, so
// the words around it keep their order. 'start' and 'end' follow each block's own direction.
const second = { id: 'second', fontFamily: LATIN, fontSize: pt(9.5), lineHeight: pt(14),
  color: col('slate'), textAlign: 'start', firstLineIndent: pt(0) };
const bodyText = { fontFamily: ARABIC, fontSize: pt(11), lineHeight: pt(LEAD),
  color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'start', // ragged: the right edge for Arabic, the left for an English block
  firstLineIndent: pt(0), paragraphSpacing: true,
  // The Arabic is never slanted; italics stay for the titles in the Latin blocks.
  emphasis: 'italic' };
// #endregion

// #region tables: the Arabic table runs with the page; the English one runs left to right
const cell = (content, extra = {}) => ({ content, ...extra });
const tableOf = (head, rows) => ({ headerRowCount: 1, columnWidths: [46, 18, 18, 18],
  rows: [head.map((h, i) => cell(h, { isHeader: true, align: i ? 'end' : 'start' })),
    ...rows.map((r) => r.map((c, i) => cell(c, { align: i ? 'end' : 'start' })))] });
const FIGURES = [ // programme, 2024, 2025, change: the Foundation's own counts
  ['كتب مترجمة إلى العربية', 'Books translated into Arabic', 28, 34],
  ['كتب مترجمة من العربية', 'Books translated from Arabic', 9, 14],
  ['منح للمترجمين', 'Translator grants', 41, 52],
  ['ورشات تدريب', 'Training workshops', 12, 18],
  ['مشاركون في الورشات', 'Workshop participants', 310, 466]];
const SPANISH = { 'Books translated into Arabic': 'Libros traducidos al árabe',
  'Books translated from Arabic': 'Libros traducidos del árabe',
  'Translator grants': 'Becas para traductores', 'Training workshops': 'Talleres de formación',
  'Workshop participants': 'Participantes en los talleres' };
const change = (a, b) => `${b > a ? '+' : ''}${Math.round((100 * (b - a)) / a)}%`;
const AR = (n) => String(n).replace(/\d/g, (d) => '٠١٢٣٤٥٦٧٨٩'[d]); // the author's ٠–٩
const tableAr = tableOf(['البرنامج', '٢٠٢٤', '٢٠٢٥', 'التغيّر'], FIGURES.map(([ar, , a, b]) =>
  [ar, AR(a), AR(b), AR(change(a, b)).replace('%', '٪')]));
const tableEn = tableOf(t({ en: ['Programme', '2024', '2025', 'Change'],
  es: ['Programa', '2024', '2025', 'Cambio'] }), FIGURES.map(([, en, a, b]) =>
  [t({ en, es: SPANISH[en] }), String(a), String(b), change(a, b)]));
// The English table has a heading of its own and no number: a generated number would print in
// the document's digits, ٢, inside the English block.
const resourceTypes = [...defaultResourceTypes('ar'), { id: 'data', name: 'Data',
  shortLabel: 'Data', captionPrefix: '', numberingTemplate: '', resetOn: 'never',
  counterFormat: 'decimal' }];
const resources = [
  { id: 'figures-ar', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tableAr }, placement: { position: 'here' },
    caption: 'أرقام البرامج في عامي ٢٠٢٤ و٢٠٢٥' },
  { id: 'figures-en', typeId: 'data', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tableEn, direction: 'ltr', styleId: 'second' },
    placement: { position: 'here' } },
];
// #endregion

// #region cover: the report's two titles on a teal band, each in its own direction
const band = { enabled: true, minHeight: mm(70), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('teal') },
    placement: { anchor: { to: 'bleed', edge: 'top-left' },
      size: { width: mm(216), height: mm(86) } } },
  // Design text takes the document's direction; an English title says 'ltr' and aligns left.
  { kind: 'text', id: 'org', content: '{attr.org}', fontFamily: ARABIC, fontSize: pt(13),
    fontWeight: 600, color: col('tint'), align: 'right',
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-SIDE), y: mm(18) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: ARABIC, fontSize: pt(50),
    fontWeight: 700, lineHeight: 1.15, color: col('paper'), align: 'right',
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-SIDE), y: mm(30) } } },
  { kind: 'text', id: 'title-2', content: '{attr.second}', direction: 'ltr', fontFamily: LATIN,
    fontSize: pt(20), fontWeight: 300, color: col('tint'), align: 'left',
    placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(SIDE), y: mm(66) } } },
] } };
// #endregion

const config = () => ({ // a factory: the engine caches resolved configs per object
  locale: 'ar', // written out, never LANG (gotcha: arabic-locale-tag)
  colorPalette, bodyText, resourceTypes,
  page: { width: mm(210), height: mm(280), dpi: 150,
    margins: { top: mm(22), bottom: mm(22), left: mm(SIDE), right: mm(SIDE), mirror: true } },
  layout: { layoutType: 'single' },
  headings: { fontFamily: ARABIC, fontWeight: 700, color: col('teal'), levels: [
    // Restated: any headings object drops the H1 break (gotcha: headings-drop-h1-break).
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, marginTop: pt(0),
      marginBottom: pt(0), advancedDesign: band },
    { level: 2, fontSize: pt(17), lineHeight: pt(26), marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  headingStyles: [{ id: 'second-head', fontFamily: LATIN, fontSize: pt(10), fontWeight: 600,
    lineHeight: pt(14), color: col('slate'), marginTop: pt(0), marginBottom: pt(4) }],
  paragraphStyles: [second,
    { id: 'colophon', fontFamily: LATIN, fontSize: pt(7.5), lineHeight: pt(10),
      color: col('slate'), textAlign: 'start', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  tableStyle: { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
    headerBackground: col('teal'), headerColor: col('paper'), headerFontFamily: ARABIC,
    headerFontSize: pt(9.5), bodyFontFamily: ARABIC, bodyFontSize: pt(10), bodyColor: col('ink'),
    cellPadding: mm(1.6) },
  tableStyles: [{ id: 'second', headerBackground: col('slate'), headerFontFamily: LATIN,
    bodyFontFamily: LATIN, bodyFontSize: pt(9), bodyColor: col('slate') }],
  captionStyle: { fontFamily: ARABIC, fontSize: pt(9.5), color: col('ink'), position: 'above',
    labelBold: true, labelColor: col('teal'), labelSeparator: ': ' },
  header: { elements: [] },
  footer: { elements: [{ kind: 'text', id: 'folio', content: '{pageNumber}', pages: 'body',
    fontFamily: ARABIC, fontSize: pt(9), fontWeight: 600, color: col('teal'), align: 'center',
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-12) } } }] },
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
Markdown样例 · 60行 · content.en.mdtitle: "التقرير السنوي ٢٠٢٥" --- # التقرير السنوي ٢٠٢٥ {org="مؤسسة دار الضاد للترجمة" second="Dar al-Dad Translation Foundation · Annual Report 2025"} ## كلمة المديرة ### Director's note {style="second-head" dir=ltr} كان عام ٢٠٢٥ أكثر أعوام المؤسسة نشاطًا منذ تأسيسها. فقد صدر في هذا العام ٣٤ كتابًا مترجمًا إلى العربية و١٤ كتابًا مترجمًا منها، ومنحنا ٥٢ منحة لمترجمين من تسعة بلدان، وأقمنا ١٨ ورشة تدريب حضرها ٤٦٦ مشاركًا ومشاركة. :::paragraphs{style="second" dir=ltr} 2025 was the busiest year in the Foundation's history. We published 34 books translated into Arabic and 14 translated from it, awarded 52 grants to translators from nine countries, and ran 18 training workshops attended by 466 people. ::: وأكثر ما يسعدنا في هذه الأرقام أن الترجمة من العربية بدأت تلحق بالترجمة إليها. فقد كان الكتاب المترجم من العربية قبل خمس سنوات يقابله أكثر من ستة كتب مترجمة إليها، وصار اليوم يقابله كتابان ونصف. وقد صدرت روايتان من الكتب التي دعمناها في سلسلة :ltr[Harbour Modern Classics]{lang=en}، وهي المرة الأولى التي تدخل فيها روايات عربية معاصرة هذه السلسلة بدعم منا. :::paragraphs{style="second" dir=ltr} What pleases us most in these figures is that translation from Arabic has begun to catch up with translation into it. Five years ago, every book we supported out of Arabic was matched by more than six into it; today the ratio is two and a half to one. Two of the novels we supported appeared in Harbour Modern Classics. ::: ## أرقام العام ### The year in figures {style="second-head" dir=ltr} يعرض الجدول التالي برامج المؤسسة الخمسة في العامين الأخيرين، والنسبة التي تغيّر بها كل برنامج. وتُحسب المنح في السنة التي صُرفت فيها، لا في السنة التي قُدّم فيها الطلب. ::resource{id="figures-ar"} :::paragraphs{style="second" dir=ltr} The table below gives the same figures in English. Grants are counted in the year they were paid, not the year they were applied for. ::: ::resource{id="figures-en"} ## البرامج ### Programmes {style="second-head" dir=ltr} **الترجمة إلى العربية.** نختار الكتب بالتشاور مع لجنة من الناشرين والمترجمين تجتمع مرتين في السنة. ومن أبرز ما صدر هذا العام ترجمة جديدة لرواية :ltr[Middlemarch]{lang=en} لجورج إليوت، ومختارات من مقالات :ltr[Michel de Montaigne]{lang=fr} في الصداقة والسفر والقراءة. :::paragraphs{style="second" dir=ltr} **Translation into Arabic.** Titles are chosen with a committee of publishers and translators that meets twice a year. This year's list includes a new translation of George Eliot's *Middlemarch* and a selection of Montaigne's essays on friendship, travel and reading. ::: **الترجمة من العربية.** نموّل نصف تكاليف الترجمة للناشر الأجنبي الذي يشتري حقوق كتاب عربي، ونرافق المترجم بمحرر يقرأ ترجمته مع النص الأصلي. وصدرت هذا العام كتب مترجمة إلى الإنجليزية والإسبانية والتركية والإندونيسية. :::paragraphs{style="second" dir=ltr} **Translation from Arabic.** We pay half the translation costs of a foreign publisher who buys the rights to an Arabic book, and pair the translator with an editor who reads the translation against the original. This year's books appeared in English, Spanish, Turkish and Indonesian. ::: **التدريب.** تستمر الورشة الواحدة خمسة أيام، ويعمل فيها المشاركون على نص واحد بإشراف مترجمَين اثنين، أحدهما ينقل إلى العربية والآخر ينقل منها. وقد أضفنا هذا العام ورشة للترجمة الأدبية للأطفال، وأخرى لترجمة الشعر. :::paragraphs{style="second" dir=ltr} **Training.** Each workshop runs for five days, and its participants work on a single text with two tutors, one translating into Arabic and one out of it. This year we added a workshop on children's literature and another on poetry. ::: :::paragraphs{style="colophon" dir=ltr} A specimen report written for the Postext Cookbook; the Foundation, its figures and its people are invented. Set in IBM Plex Sans Arabic and IBM Plex Sans (SIL OFL) · Text: CC BY 4.0. :::
`; // content.<lang>.md: the Arabic, with English or Spanish // ─── 3 · Fonts ────────────────────────────────────────────────────────────── const FONTS = { // every face the pages use, loaded before the build (gotcha: fonts-first) 'IBM Plex Sans Arabic': ['400', '600', '700'], // ARABIC: text, headings, tables, folios 'IBM Plex Sans': ['300', '400', '400i', '600'], // LATIN: the second language, its table }; // ─── 4 · Build & show ─────────────────────────────────────────────────────── await loadFonts(FONTS, markdown); // Each Arabic face's letters live in a file of their own (gotcha: arabic-fonts-subset). await loadArabicFonts(FONTS, markdown + JSON.stringify(resources)); const doc = await buildWithFonts(() => buildDocument({ markdown, resources }, config()), markdown); showBook(doc, { title: t({ en: 'A bilingual Arabic–English report', es: 'Un informe bilingüe árabe-español' }) }); offerPdf(() => renderToPdf(doc, { fontProvider: arabicPdfProvider }), `${RECIPE}.pdf`);
工具包 · core, fonts, viewer, pdf, arabic, book:每道食谱都相同 · 411行// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ───── // ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook ───────── function mm(value) { return { value, unit: 'mm' }; } function pt(value) { return { value, unit: 'pt' }; } function em(value) { return { value, unit: 'em' }; } /** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */ function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; } /** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */ function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; } // ─── Kit · fonts v1 ── the same in every recipe · postext.dev/cookbook ──────── // Postext measures text with the faces the browser has loaded, and caches the // widths, so every face must be ready before the first build. Faces come from // Fontsource: the same static files the PDF embeds, so screen and PDF agree. /** faces = { 'Family Name': ['400', '400i', '700'] }. `text` is the sample: * letters beyond Latin-1 (č, ł, ő…) also load the latin-ext files. With * `optional`, a face Fontsource does not ship is skipped instead of failing. * Resolves to the number of faces added. */ async function loadFonts(faces, text = '', { optional = false } = {}) { kitStatus('Loading fonts…'); const ranges = { latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,' + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD', 'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,' + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF', }; const subsets = /[Ā-˿Ḁ-ỿ]/.test(text) ? ['latin', 'latin-ext'] : ['latin']; const jobs = []; let added = 0; for (const [family, specs] of Object.entries(faces)) { const id = fontsourceId(family); const meta = optional ? await fontsourceMeta(family) : null; for (const spec of new Set(specs)) { const weight = parseInt(spec, 10); const style = spec.endsWith('i') ? 'italic' : 'normal'; if (hasFace(family, weight, style)) continue; if (optional && !(meta?.weights.includes(weight) && meta.styles.includes(style))) continue; for (const subset of subsets) { const url = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`; const face = new FontFace(family, `url(${url}) format('woff2')`, { weight: String(weight), style, unicodeRange: ranges[subset] }); jobs.push(face.load().then((ready) => { document.fonts.add(ready); added++; }, () => { if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`); })); } } } await Promise.all(jobs).catch((error) => { kitFail(error); throw error; }); return added; } /** Runs `build` (a buildDocument or buildBundle call) and checks the faces * the pages use. A regular face missing from FONTS is loaded with a warning; * bold and italic variants are loaded when the family ships them. Then the * measurement caches are cleared and the build runs again. */ async function buildWithFonts(build, text = '') { const tried = new Set(); for (let round = 0; round < 3; round++) { kitStatus('Laying out…'); await new Promise(requestAnimationFrame); // let the status paint first const result = await Promise.resolve().then(build).catch((error) => { kitFail(error); throw error; }); const wanted = { base: {}, variants: {} }; for (const { font, base } of [result].flat().flatMap(fontStringsOf)) { const { family, weight, style } = parseFont(font); const key = `${family}|${weight}|${style}`; if (tried.has(key) || hasFace(family, weight, style)) continue; tried.add(key); (wanted[base ? 'base' : 'variants'][family] ??= []).push(`${weight}${style === 'italic' ? 'i' : ''}`); } if (Object.keys(wanted.base).length) { console.warn(`[cookbook] FONTS does not list ${JSON.stringify(wanted.base)}: loading them.`); } const added = await loadFonts(wanted.base, text) + await loadFonts(wanted.variants, text, { optional: true }); if (added === 0) return result; clearMeasurementCache(); } throw new Error('The fonts did not settle after three builds.'); } /** Every font string of the layout. `base` marks a block's own face; its * bold, italic and bold-italic variants are listed whether or not used. */ function fontStringsOf(doc) { const found = new Map(); const walk = (node) => { if (!node || typeof node !== 'object') return; if (Array.isArray(node)) { node.forEach(walk); return; } for (const [key, value] of Object.entries(node)) { if (typeof value === 'string' && /fontString$/i.test(key)) { found.set(value, found.get(value) || key === 'fontString'); } else if (value && typeof value === 'object') walk(value); } }; walk(doc.pages); walk(doc.blocks); return [...found].map(([font, base]) => ({ font, base })); } /** '700 37.5px Open Sans' / 'italic 400 13px "Source Serif 4"' → { family, weight, style }. * A string with no weight ('95.8px Young Serif', from a design text) is 400. */ function parseFont(font) { const m = /^(?:(italic|oblique)\s+)?(?:small-caps\s+)?(?:(\d+|bold|normal)\s+)?[\d.]+px\s+(.+)$/.exec(font.trim()); if (!m) throw new Error(`Unexpected font string: ${font}`); const weight = m[2] === 'bold' ? 700 : !m[2] || m[2] === 'normal' ? 400 : Number(m[2]); return { family: m[3].replace(/^["']|["']$/g, ''), weight, style: m[1] ? 'italic' : 'normal' }; } /** True when a loaded FontFace covers exactly this family, weight and style * (document.fonts.check() is also true for families nobody declared). */ function hasFace(family, weight, style) { for (const face of document.fonts) { if (face.status !== 'loaded' || face.style !== style) continue; if (face.family.replace(/^["']|["']$/g, '') !== family) continue; const [low, high = low] = face.weight.split(' ').map(Number); if (weight >= low && weight <= high) return true; } return false; } /** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */ function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); } /** The weights and styles a family ships ({ weights: [400, 700], styles: ['normal', 'italic'] }), or null. */ function fontsourceMeta(family) { fontsourceMeta.cache ??= new Map(); const id = fontsourceId(family); if (!fontsourceMeta.cache.has(id)) { fontsourceMeta.cache.set(id, fetch(`https://api.fontsource.org/v1/fonts/${id}`) .then((res) => (res.ok ? res.json() : null), () => null)); } return fontsourceMeta.cache.get(id); } // ─── Kit · viewer v1 ── the same in every recipe · postext.dev/cookbook ─────── /** Shows the pages as facing spreads on a dark desk: the first page is a * recto on its own, then verso | recto pairs, as in a bound book. Pages * are painted when they scroll near the screen. */ function showPages(docs, { title, width = 460 } = {}) { const root = viewer(title); const pages = [docs].flat().flatMap((doc) => doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index }))); const spreads = []; let verso = null; for (const p of pages) { if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; } else { spreads.push([verso, p]); verso = null; } } if (verso) spreads.push([verso, null]); const density = Math.min(window.devicePixelRatio || 1, 2); showPages.painter?.disconnect(); const painter = new IntersectionObserver((entries) => { for (const { isIntersecting, target } of entries) { if (!isIntersecting) continue; painter.unobserve(target); const { doc, page } = target.postext; renderPageToCanvas(page, doc, target, { scale: (width * density) / page.width }); } }, { rootMargin: '800px' }); showPages.painter = painter; root.replaceChildren(...spreads.map((pair) => { const spread = document.createElement('div'); spread.className = 'pt-spread'; for (const p of pair) { const figure = document.createElement('figure'); if (p) { const label = p.page.pageLabel || String(p.n + 1); const canvas = document.createElement('canvas'); canvas.postext = p; canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`; canvas.setAttribute('role', 'img'); canvas.setAttribute('aria-label', `Page ${label}`); const folio = document.createElement('figcaption'); folio.textContent = label; figure.append(canvas, folio); painter.observe(canvas); } else figure.className = 'pt-blank'; spread.append(figure); } return spread; })); kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`); document.documentElement.dataset.postext = 'ready'; return pages.length; } /** The desk, the bar and the error reporting, created once. */ function viewer(title) { if (!document.getElementById('pt-kit')) { document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit"> :root { color-scheme: dark; } body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; } #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px); border-bottom: 1px solid #23262d; } #pt-bar strong { color: #f4f1ea; font-weight: 600; } #pt-actions { display: flex; gap: 12px; margin-left: auto; } #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; } #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; } .pt-spread { display: flex; } .pt-spread figure { margin: 0; width: min(460px, 44vw); } .pt-spread canvas { display: block; width: 100%; background: #fff; box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); } .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); } .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif; letter-spacing: .18em; text-transform: uppercase; color: #6c7079; } .pt-blank { visibility: hidden; } @media (max-width: 760px) { .pt-spread { flex-direction: column; gap: 32px; } .pt-spread figure { width: min(460px, 92vw); } .pt-blank { display: none; } } </style>`); document.body.insertAdjacentHTML('afterbegin', '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>'); document.getElementById('pt-title').textContent = document.title || 'Postext'; addEventListener('error', (event) => kitFail(event.error ?? event.message)); addEventListener('unhandledrejection', (event) => kitFail(event.reason)); } if (title) document.getElementById('pt-title').textContent = title; return document.getElementById('pages') ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' })); } function kitStatus(text) { viewer(); document.getElementById('pt-status').textContent = text; } function kitFail(error) { document.documentElement.dataset.postext = 'error'; kitStatus(`Error: ${error?.message ?? error}`); } // ─── Kit · pdf v1 ── the same in every recipe that exports a PDF ────────────── /** postext-pdf embeds TrueType bytes. Fetch the Fontsource file the screen * used, snapping to a weight the family ships and falling back to upright * when it has no italic: the PDF asks for every face a block could use. */ async function fontsourceProvider(family, weight, style) { const id = fontsourceId(family); const meta = await fontsourceMeta(family); const weights = meta?.weights?.length ? meta.weights : [400, 700]; const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)); const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style; const res = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-${w}-${s}.woff2`); if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} (${res.status})`); return decompressWoff2(new Uint8Array(await res.arrayBuffer())); } /** A "Build the PDF" button in the bar. Once built: "Open the PDF" (a new * tab, since CodePen's preview frame cannot show PDFs) and a download link. */ function offerPdf(makePdf, filename) { viewer(); const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' }); button.dataset.postextPdf = filename; button.addEventListener('click', async () => { button.disabled = true; button.textContent = 'Building the PDF…'; try { const bytes = await makePdf(); const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' })); const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`; button.replaceWith( Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }), Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` })); } catch (error) { button.disabled = false; button.textContent = 'Build the PDF'; kitFail(error); } }); document.getElementById('pt-actions').append(button); } // ─── Kit · arabic v1 ── Arabic-script faces · postext.dev/cookbook ─────────── // Fontsource ships an Arabic family as one file per subset and weight: the // `arabic` file holds the letters, the harakat, the Arabic-Indic digits, the // Arabic punctuation and the presentation forms; `latin` and `latin-ext` // hold the rest. loadFonts loads the latin files; this block adds the arabic // file of every Arabic family, for the canvas and for the PDF, which shapes // the letters with HarfBuzz from the same bytes. /** The code points of Fontsource's `arabic` subset, as its stylesheets * declare them (the same unicode-range the browser picks the file by). A * function, not a const: the kit is inlined after the recipe's top-level * awaits, and a const read before its line throws, where a function * declaration is hoisted. */ function arabicRange() { return 'U+0600-06FF,U+0750-077F,U+0870-088E,U+0890-0891,U+0897-08E1,U+08E3-08FF,' + 'U+200C-200E,U+2010-2011,U+204F,U+2E41,U+FB50-FDFF,U+FE70-FE74,U+FE76-FEFC,U+102E0-102FB,' + 'U+10E60-10E7E,U+10EC2-10EC4,U+10EFC-10EFF,U+1EE00-1EEFF'; } /** Whether code point `cp` is in the arabic file. */ function inArabicRange(cp) { inArabicRange.ranges ??= arabicRange().split(',').map((part) => { const [lo, hi = lo] = part.slice(2).split('-'); return [parseInt(lo, 16), parseInt(hi, 16)]; }); return inArabicRange.ranges.some(([lo, hi]) => cp >= lo && cp <= hi); } /** Whether Fontsource serves `family` with an `arabic` subset. Fails when * the API does not answer: an Arabic face taken for a Latin one would set * its letters in a system face. */ async function isArabicFamily(family) { const meta = await fontsourceMeta(family); if (!meta) throw new Error(`api.fontsource.org did not describe ${family}: reload to try again`); return !!meta.subsets?.includes('arabic'); } /** The arabic file of a face. */ function arabicFileUrl(family, weight, style) { const id = fontsourceId(family); return `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-arabic-${weight}-${style}.woff2`; } /** faces = { Amiri: ['400', '700'] }, as for loadFonts, after it: the whole * FONTS object may be passed, its families without an arabic subset are * left alone. Adds the arabic file of every listed weight of each Arabic * family (the latin files come from loadFonts) and loads it. `text` is * the sample: fails when it holds an Arabic-script character the arabic * file does not cover. List every weight the pages set in Arabic: a weight * left to buildWithFonts gets the latin file only, and its Arabic letters * fall back to a system face. Resolves to the number of files loaded. */ async function loadArabicFonts(faces, text = '') { kitStatus('Loading fonts…'); let loaded = 0; try { const outside = [...new Set(text)].filter((ch) => /\p{Script=Arabic}/u.test(ch) && !inArabicRange(ch.codePointAt(0))); if (outside.length) throw new Error(`Fontsource's arabic files have no ${outside.slice(0, 12).join(' ')}`); for (const [family, specs] of Object.entries(faces)) { if (!(await isArabicFamily(family))) continue; for (const spec of new Set(specs)) { const weight = parseInt(spec, 10); const style = spec.endsWith('i') ? 'italic' : 'normal'; const face = new FontFace(family, `url(${arabicFileUrl(family, weight, style)}) format('woff2')`, { weight: String(weight), style, unicodeRange: arabicRange() }); document.fonts.add(await face.load().catch(() => { throw new Error(`Fontsource has no arabic file for ${family} ${weight} ${style}`); })); loaded++; } } } catch (error) { kitFail(error); throw error; } return loaded; } /** The PDF font provider for recipes with Arabic faces: a family with an * arabic subset gets its arabic file when its pages set Arabic letters * (`request.codePoints`), then its latin file, and its latin-ext file for * the letters beyond latin (transliteration: ā ḥ ʿ). The arabic file comes * first: it also holds the space and the brackets, so a line of Arabic is * shaped as one run and not cut at every space. Any other family goes to * fontsourceProvider (the "pdf" block). */ async function arabicPdfProvider(family, weight, style, request) { if (!(await isArabicFamily(family))) return fontsourceProvider(family, weight, style); const meta = await fontsourceMeta(family); const weights = meta.weights?.length ? meta.weights : [400, 700]; const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)); const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style; const wanted = [...(request?.codePoints ?? [])]; const id = fontsourceId(family); const urls = []; if (!wanted.length || wanted.some(inArabicRange)) urls.push(arabicFileUrl(family, w, s)); urls.push(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-${w}-${s}.woff2`); if (meta.subsets.includes('latin-ext') && wanted.some((cp) => /[Ā-˿Ḁ-ỿ]/u.test(String.fromCodePoint(cp)))) { urls.push(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-ext-${w}-${s}.woff2`); } return Promise.all(urls.map(async (url) => { const res = await fetch(url); if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`); return decompressWoff2(new Uint8Array(await res.arrayBuffer())); })); } // ─── Kit · book v1 ── books bound on either edge · postext.dev/cookbook ────── // A book bound on the right (Arabic, Hebrew or Persian text, vertical // Chinese, or page.binding 'right') opens from what a Latin reader calls // the back: page 1 lies alone on the left of the spine, then [3 | 2]. /** showPages for a book bound on either edge. A right-bound book (the * document says so: doc.binding is 'right' for page.binding 'right', for * text that runs right to left and for vertical text, when the binding is * left to 'auto') lies on the desk as it opens: page 1 alone on the left * of the spine, then [3 | 2], the spine shade on each page's inner edge. * `binding` ('left' | 'right') overrides the document's. */ function showBook(docs, { binding, ...options } = {}) { const count = showPages(docs, options); const right = (binding ?? [docs].flat()[0]?.binding) === 'right'; if (!document.getElementById('pt-kit-book')) { // The pages keep direction ltr, as in a left-bound book: a canvas takes // the direction its element inherits, and under the spread's rtl a run // painted for an ltr canvas would end where the engine starts it. document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit-book"> .pt-spread[dir="rtl"] canvas { direction: ltr; } .pt-spread[dir="rtl"] figure:first-child canvas { box-shadow: inset 14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); } </style>`); } // Each pair stays [verso, recto] in the page; right to left, the verso // sits on the right. Phones stack the pages in reading order either way. for (const spread of document.querySelectorAll('#pages > .pt-spread')) spread.dir = right ? 'rtl' : 'ltr'; document.getElementById('pages').dataset.binding = right ? 'right' : 'left'; return count; } // ─── /Kit ───────────────────────────────────────────────────────────────────────

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

变化

#把英文放在前面

给不读阿拉伯文的理事会看的报告,互换两种语言的角色:英文文档,英文块不加标记,阿拉伯文块标记{dir=rtl}。

-  locale: 'ar', // written out, never LANG (gotcha: arabic-locale-tag)
+  locale: 'en-us', // Arabic blocks then carry {dir=rtl}

常见问题

易错点

阿拉伯文书标记为'ar',不要用LANG

食谱的版本是en和es,但阿拉伯文示例在两个版本里都是阿拉伯文:`locale: LANG`会让它从左向右排、左装订、页码印成1 2 3,并把图标注为Figure或Figura。自己写出标记:'ar'(阿拉伯-印度数字,马什里克惯例),或带地区的'ar-EG'、'ar-SA';马格里布版本用欧洲数字,写'ar-MA'、'ar-DZ'或'ar-TN'。只引用阿拉伯文的拉丁文页面保留自己的locale。 从右向左的文字 →

易错点

阿拉伯文字体需要通过arabic块加载其arabic文件

Fontsource把Amiri、Noto Naskh Arabic或Scheherazade New按子集分成多个文件提供,阿拉伯字母在arabic文件里。loadFonts只获取latin(以及latin-ext),所以屏幕上的阿拉伯文来自系统字体,测量不准;fontsourceProvider交给PDF的也是这个latin文件,印出来是空框。列出kit中的arabic块,在loadFonts之后调用loadArabicFonts(FONTS, markdown),并在FONTS中列出页面用于阿拉伯文的每个字重,再给renderToPdf传fontProvider: arabicPdfProvider。 阿拉伯文字体 →

易错点

传入任何headings对象都会关掉H1换页

默认情况下,H1换页到右页(always-odd),但只要传入headings对象,这个默认值就会被重置,于是各章接排,span: 'page'也不起作用。在每份配置中重新写明headings.levels[0].breakBefore: { enabled: true, parity }。 从右页开始的章 →

易错点

排版前加载所有字体

排版用浏览器已加载的字体测量文字,并缓存宽度,所以首次构建之后才到的字体会造成断行错误,PDF也不再与屏幕一致。先加载所有字重和样式;有字体迟到时,重新构建前调用clearMeasurementCache()。 排版前加载字体 →

  • 引擎在英文块里生成的数字,比如列表编号或图注标签,仍然使用文档的数字系统(阿拉伯文报告里是٢)。给这类表格一个不计数的资源类型,或者自己写出编号。

致谢

文本
  • The annual report of an invented translation foundation, written in Arabic, English and Spanish for the recipe · Postext Cookbook · 原创
字体
IBM Plex Sans Arabic (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)
沙盒PDF