Pular para o conteúdo principal
Receita número 106

Receitas · Capítulo 2 · Tipo e texto

Um relatório bilíngue árabe-inglês

Relatório anual em árabe com o inglês ao lado: {dir=ltr} em cada bloco inglês, :ltr[…] para nomes latinos nas linhas árabes e uma tabela da esquerda à direita.

Nesta página
Saída
Canvas · PDF
Postext
Testada com o Postext 1.65.0
Requer ≥ 1.25.0 · postext-pdf ≥ 1.25.0
Licença
Atualizada em 10 de out. de 2026
Código MIT · Texto CC BY 4.0

p. ١ · 1 de 3

  • Amostra em inglês: ainda sem edição em português
  • Refile 210 × 280 mm
  • 1 coluna
  • IBM Plex Sans Arabic 11/18
  • IBM Plex Sans
  • 3 páginas
  • Nível
  • Postext 1.63.6
  • Diagramado em 197 ms
  • 143 linhas de código

Em poucas palavras

O relatório anual de uma fundação escrito em árabe, com cada parágrafo seguido da versão em inglês. A página mistura as duas direções sem que as palavras, os números ou as tabelas saiam de ordem.

O que você vai compor

O relatório de 2025 de uma fundação de tradução imaginária, Dar al-Dad, numa página de 210 × 280 mm (a largura do A4) em IBM Plex Sans Arabic e IBM Plex Sans, as duas metades de uma mesma família. O relatório é árabe: corre da direita para a esquerda e numera as páginas ٢, ٣. Cada parágrafo árabe vem seguido da versão em inglês, menor e em cinza-ardósia, composta da esquerda para a direita e em bandeira à direita; cada título árabe leva um rótulo em inglês na outra margem. Os nomes latinos dentro das frases árabes mantêm a própria ordem, e os números do ano aparecem duas vezes, numa tabela árabe lida a partir da direita e numa inglesa lida a partir da esquerda. Na edição espanhola, a segunda língua é o espanhol.

Esta receita responde a

  • Como misturo parágrafos, números e tabelas em árabe e em inglês na mesma página?

A resposta curta

script.js · linhas 32–45no código completo
// 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' };

Ingredientes

Tipografia
IBM Plex Sans Arabic, IBM Plex Sans (SIL OFL 1.1)
Materiais
Nenhum: todas as imagens são desenhadas em código

Preparo

#1 · A segunda língua em blocos marcados

O código está na resposta curta, mais acima. O documento é árabe, por isso todo bloco corre da direita para a esquerda até o Markdown dizer o contrário: {dir=ltr} num contêiner :::paragraphs ou num título inverte aquele bloco, e textAlign: 'start' leva cada bloco para o lado em que ele começa, a direita no árabe e a esquerda no inglês (Direção do documento, do bloco e do texto na linha). Um nome latino dentro de uma linha árabe, :ltr[Harbour Modern Classics], é um isolamento: o algoritmo bidirecional o trata como uma peça neutra única, e as palavras árabes e a vírgula em volta dele ficam no lugar (Isolamentos). emphasis: 'italic' mantém Middlemarch em itálico no texto inglês; o motor nunca inclina uma letra árabe, seja qual for a configuração.

#2 · Uma tabela para cada direção

script.js · linhas 49–82no código completo
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' } },
];

A tabela árabe segue o documento: a primeira coluna, o programa, fica à direita, e align: 'end' encosta os números na borda esquerda das células. A tabela inglesa define direction: 'ltr', de modo que a primeira coluna fica à esquerda e 'end' quer dizer a borda direita (O que significam esquerda, direita, início e fim). Os números árabes foram digitados em ٠–٩ e os ingleses em 0–9: os algarismos do documento só valem para os números que o motor escreve, como o número da tabela na legenda, جدول ١-١. Por isso a tabela inglesa tem um tipo próprio, sem contador: um número ali sairia como ٢.

#3 · Dois títulos numa faixa

script.js · linhas 86–102no código completo
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) } } },
] } };

A página de rosto é o design do título de nível 1. O design de um título é composto no fluxo e espelhado com a página, por isso suas âncoras se referem aos lados do texto: top-left é a direita da folha, onde começam o nome e o título árabes, e top-right a esquerda, onde começa o título inglês. O texto de design segue a direção do documento, por isso as linhas árabes não precisam de mais nada; o título inglês define direction: 'ltr'. A faixa é uma caixa ancorada na sangria, com 86 mm de altura, e o minHeight da abertura traz a carta da diretora para logo abaixo dela.

A receita completa

Sandbox
// ═══ 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

O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)

Variações

#Pôr o inglês primeiro

Um relatório para um conselho que não lê árabe troca os papéis: um documento em inglês, com os blocos sem marca, e os blocos árabes marcados com {dir=rtl}.

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

Erros comuns

Erro comum

Marque um livro árabe como 'ar', não com LANG

As edições de uma receita são en e es, mas uma amostra árabe é árabe nas duas: `locale: LANG` a comporia da esquerda para a direita, a encadernaria pela esquerda, numeraria as suas páginas 1 2 3 e chamaria as suas figuras de Figure ou Figura. Desde o postext 1.30 a marcação é também o idioma em que o texto é composto (em que é medido, pintado e incorporado), então, sob uma marcação inglesa ou espanhola, uma fonte como a Markazi Text não desenha as formas árabes das aspas angulares e dos pontos, e as linhas quebram em outro ponto. Escreva você mesmo a marcação: 'ar' (algarismos arábico-índicos, a convenção do Machrek), uma região como 'ar-EG' ou 'ar-SA', ou 'ar-MA', 'ar-DZ' ou 'ar-TN' para uma edição magrebina com algarismos europeus. Uma página latina que só cita árabe mantém o seu próprio locale. Texto da direita para a esquerda →

Erro comum

Fontes árabes precisam do seu arquivo arabic, pelo bloco arabic

O Fontsource serve Amiri, Noto Naskh Arabic ou Scheherazade New em um arquivo por subconjunto, e as letras árabes estão no arquivo arabic. loadFonts baixa só latin (e latin-ext), então na tela o árabe vem de uma fonte do sistema e é medido errado, e o fontsourceProvider entrega ao PDF esse arquivo latin, que imprime caixas vazias. Inclua o bloco arabic do kit, chame loadArabicFonts(FONTS, markdown) depois de loadFonts, com todos os pesos que as páginas usam em árabe listados em FONTS, e passe a renderToPdf fontProvider: arabicPdfProvider. Fontes árabes →

  • Um número que o motor escreve dentro de um bloco inglês, seja um número de lista ou o rótulo de uma legenda, continua usando os algarismos do documento (٢ num relatório árabe). Dê a essas tabelas um tipo de recurso sem contador, ou escreva você mesmo os números.

Créditos

Texto
  • The annual report of an invented translation foundation, written in Arabic, English and Spanish for the recipe · Postext Cookbook · original
Fontes
IBM Plex Sans Arabic (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)
SandboxPDF