In breve
Il rapporto annuale di una fondazione scritto in arabo, con ogni paragrafo seguito dalla sua versione inglese. La pagina mescola le due direzioni di scrittura senza che parole, numeri o tabelle finiscano fuori posto.
Che cosa comporrai
Il rapporto annuale 2025 di una fondazione di traduzione immaginaria, Dar al-Dad, su una pagina larga come un A4, 210 × 280 mm, in IBM Plex Sans Arabic e IBM Plex Sans, le due metà di un’unica famiglia di caratteri. Il rapporto è in arabo: va da destra a sinistra e numera le pagine ٢, ٣. Ogni paragrafo arabo è seguito dalla sua versione inglese, più piccola e in grigio ardesia, composta da sinistra a destra e in bandiera sulla destra; ogni titolo arabo ha un’etichetta inglese sul margine opposto. I nomi latini nelle frasi arabe mantengono il loro ordine, e le cifre dell’anno compaiono due volte, in una tabella araba che si legge da destra e in una inglese che si legge da sinistra. Nell’edizione spagnola la seconda lingua è lo spagnolo.
Questa ricetta risponde a
- Come mescolo paragrafi, numeri e tabelle in arabo e in inglese nella stessa pagina?
La risposta breve
// 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' };
Ingredienti
- Funzionalità
- Paragrafi nell’altra direzioneSequenze nell’altra direzioneTesto da destra a sinistraFont arabiL’arabo come lingua del documentoCifre dei numeri generatiTabelle dai datiStile delle tabelleStili di tabella con nomeStile delle didascalieTipi di risorsa personalizzatiAperture progettateStili di titoloStili di paragrafoTavolozza di colori semanticaEsportazione in PDF
- Usa anche
- Attributi dei titoliFigure proprio quiFigura e Tabella nella tua linguaTestatine secondo il ruolo della paginaFont incorporati nel PDFLibri rilegati a destra
- Tipo
- IBM Plex Sans Arabic, IBM Plex Sans (SIL OFL 1.1)
- Risorse
- Nessuna: ogni immagine è disegnata nel codice
Preparazione
#1 · La seconda lingua come blocchi marcati
Il codice è nella risposta breve qui sopra. Il documento è in arabo, quindi ogni blocco va da destra a sinistra finché il Markdown non indica altro: {dir=ltr} su un blocco :::paragraphs o su un titolo gira quel blocco, e textAlign: 'start' manda ogni blocco verso il lato da cui comincia, a destra per l’arabo e a sinistra per l’inglese (Direzione del documento, dei blocchi e del testo in linea). Un nome latino in una riga araba, :ltr[Harbour Modern Classics], è un isolato: l’algoritmo bidi lo tratta come un unico pezzo neutro, così le parole arabe e la virgola che lo circondano restano al loro posto (Isolati). emphasis: 'italic' mantiene Middlemarch in corsivo nel testo inglese; il motore non inclina mai una lettera araba, qualunque sia l’impostazione.
#2 · Una tabella per ogni direzione
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)).replaceAll('%', '٪')]));
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' } },
];
La tabella araba segue il documento: la sua prima colonna, il programma, sta a destra, e align: 'end' porta i numeri contro il bordo sinistro delle celle. La tabella inglese imposta direction: 'ltr', quindi la prima colonna sta a sinistra e 'end' indica il bordo destro (Che cosa significano sinistra, destra, inizio e fine). Le cifre arabe sono digitate in ٠–٩, quelle inglesi in 0–9: le cifre del documento valgono solo per i numeri che scrive il motore, come il numero della tabella nella didascalia, جدول ١-١. Per questo anche la tabella inglese ha un tipo tutto suo senza contatore, perché lì un numero verrebbe stampato come ٢.
#3 · Due titoli su una fascia
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) } } },
// A heading's design is set in the flow and mirrored with the page: 'left' is the side the
// text starts on, the sheet's right in this book, and 'right' its left. Design text takes
// the document's direction; the English title says 'ltr' and starts from the sheet's left.
{ kind: 'text', id: 'org', content: '{attr.org}', fontFamily: ARABIC, fontSize: pt(13),
fontWeight: 600, color: col('tint'), align: 'start',
placement: { anchor: { to: 'page', edge: 'top-left' }, 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: 'start',
placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(SIDE), y: mm(30) } } },
{ kind: 'text', id: 'title-2', content: '{attr.second}', direction: 'ltr', fontFamily: LATIN,
fontSize: pt(18), fontWeight: 300, color: col('tint'), align: 'start',
placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-SIDE), y: mm(66) } } },
] } };
La copertina è la grafica del titolo di livello 1. La grafica di un titolo si compone nel flusso e si specchia con la pagina, quindi i suoi ancoraggi indicano i lati del testo: top-left è la destra del foglio, dove cominciano il nome e il titolo arabi, e top-right la sua sinistra, dove comincia il titolo inglese. Il testo della grafica prende la direzione del documento, quindi le righe arabe non hanno bisogno d’altro; il titolo inglese imposta direction: 'ltr'. La fascia è un riquadro ancorato all’abbondanza, alto 86 mm, e il minHeight dell’apertura porta la nota del direttore sotto di essa.
La ricetta completa
// ═══ 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.25.0
import {
buildDocument, withLoadedFonts, renderPageToCanvas, 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
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Metti l’inglese per primo
Un rapporto per un consiglio che non legge l’arabo scambia i ruoli: un documento inglese con i blocchi non marcati, e quelli arabi marcati {dir=rtl}.
- locale: 'ar', // written out, never LANG (gotcha: arabic-locale-tag)
+ locale: 'en-us', // Arabic blocks then carry {dir=rtl}Errori frequenti
Errore frequente
Assegna a un libro arabo il tag 'ar', non LANG
Le edizioni di una ricetta sono en ed es, ma un esempio arabo è arabo in entrambe: `locale: LANG` lo comporrebbe da sinistra a destra, lo rilegherebbe a sinistra, numererebbe le pagine 1 2 3 e darebbe alle figure didascalie Figure o Figura. Da postext 1.30 il tag è anche la lingua usata per lo shaping del testo (misura, disegno e incorporamento), quindi con un tag inglese o spagnolo un carattere come Markazi Text non disegna le forme arabe delle sue virgolette basse e dei suoi segni di interpunzione, e le righe vanno a capo altrove. Scrivi tu il tag: 'ar' (cifre arabo-indiane, la convenzione del Mashriq), una regione come 'ar-EG' o 'ar-SA', oppure 'ar-MA', 'ar-DZ' o 'ar-TN' per un’edizione del Maghreb con cifre europee. Una pagina latina che si limita a citare l’arabo mantiene la propria lingua. Testo da destra a sinistra →
Errore frequente
I caratteri arabi hanno bisogno del loro file arabic, tramite il blocco arabic
Fontsource serve Amiri, Noto Naskh Arabic o Scheherazade New come un file per sottoinsieme, e le lettere arabe stanno nel file arabic. loadFonts scarica solo latin (e latin-ext), così a schermo l’arabo viene da un font di sistema ed è misurato male, e fontsourceProvider passa al PDF quel file latin, che stampa riquadri vuoti. Elenca il blocco arabic del kit, chiama loadArabicFonts(FONTS, markdown) dopo loadFonts, con ogni peso che le pagine compongono in arabo elencato in FONTS, e passa a renderToPdf fontProvider: arabicPdfProvider. Font arabi →
- Un numero che il motore scrive in un blocco inglese, il numero di un elenco o l’etichetta di una didascalia, prende comunque le cifre del documento (٢ in un rapporto arabo). Dai a queste tabelle un tipo di risorsa senza contatore, oppure scrivi i numeri tu.
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- The annual report of an invented translation foundation, written in Arabic, English and Spanish for the recipe · Postext Cookbook · originale
- Font
- IBM Plex Sans Arabic (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


