Em poucas palavras
Um folheto de dois lados sobre um velho moinho de maré, em inglês e espanhol. Mostra como salvar um documento com as fontes e imagens num só arquivo e depois tirar dele as mesmas páginas.
O que você vai compor
Os dois lados de um folheto de visita no formato DL, 99 × 210 mm, para um moinho de maré num estuário inventado. A frente é um só desenho: uma roda de moinho na linha d’água, com a metade de cima sobre a areia e a de baixo clara sob a água azul, o título em DM Serif Display itálico de 50 pt e uma aba azul que nomeia a edição, EN ou ES. O verso abre com o moinho em corte e segue com o texto em DM Sans justificada, o horário numa tabela de cabeçalho azul, legendas em Instrument Sans, um colofão e uma faixa azul com a editora. Cada edição é gravada num arquivo .postext, e cada página aqui é diagramada a partir dos bytes desse arquivo, com as fontes e os desenhos que ele leva.
Esta receita responde a
- Como abro um arquivo .postext e o renderizo com as próprias fontes, imagens e configuração?
- Como crio um pacote .postext a partir do código, para passar um documento ao Sandbox ou a outro programa?
- Como publico o mesmo livro em dois idiomas a partir de um só projeto?
- Como faço os rótulos “Figura” e “Tabela” saírem no idioma do meu documento?
A resposta curta
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
Ingredientes
- Funcionalidades
- Pacotes .postextFigura e Tabela no seu idiomaSuas próprias fontesHifenização e idioma do documentoLegendas numeradasCitações que posicionam as figurasFiguras exatamente aquiEspaço vertical explícitoLivros compostos capítulo a capítuloCapas, folhas de rosto e colofõesEstilos de títuloAtributos de títuloAberturas desenhadasTextos, fios e caixas nos designs de páginaImagens nos designs de páginaMetadados do documentoEstilo de legendaEstilo de tabelaExportação para PDFFontes incorporadas ao PDF
- Também usa
- Faixa de capítulo em largura totalQuebras de página e de colunaCabeços por tipo de páginaEstilos de parágrafoTipos de recurso personalizados
- Tipografia
- DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
- Materiais
- Nenhum: todas as imagens são desenhadas em código
Preparo
#1 · Gravar a edição e ler de volta só os bytes
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
createBundle compacta num zip o capítulo, a configuração, os recursos e todos os arquivos que eles citam; openBundle não recebe nada além desses bytes. As fontes vêm de loadBundleFonts, os desenhos de registerBundleImages e o design de bundle.config. Uma fonte deixada fora de files sai na fonte de reserva do navegador, e um desenho que fica de fora é descartado com um aviso, e a referência a ele imprime (?). Dentro do zip, cada fileId vira um caminho (mill.svg passa a ser resources/mill.svg), e os recursos e o customFonts que openBundle devolve já usam os nomes novos (abrir um pacote).
#2 · Pôr as fontes no arquivo
const customFonts = Object.entries(FONTS).map(([name, specs]) => ({ name,
variants: specs.map((spec) => ({ weight: parseInt(spec, 10), format: 'woff2',
style: spec.endsWith('i') ? 'italic' : 'normal', fileId: `${fontsourceId(name)}-${spec}` })),
}));
// The bytes: Fontsource's static woff2 files, latin subset, which covers the Spanish text too.
const faceFiles = Object.fromEntries(await Promise.all(customFonts.flatMap(({ name, variants }) =>
variants.map(async ({ weight, style, fileId }) => {
const id = fontsourceId(name);
const res = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/`
+ `${id}-latin-${weight}-${style}.woff2`);
if (!res.ok) throw new Error(`Fontsource has no ${name} ${weight} ${style}`);
return [fileId, new Uint8Array(await res.arrayBuffer())];
}))));
Um pacote leva uma fonte quando customFonts a cita e files guarda os bytes dela sob o fileId da variante; createBundle grava a DM Sans 400 como fonts/dm-sans-400-normal.woff2. O pen baixa os sete arquivos woff2 da Fontsource, mas não registra nenhum: loadBundleFonts acrescenta as cópias do pacote a document.fonts antes de buildBundle medir uma linha, e o PDF pega as fontes desses mesmos sete arquivos.
#3 · Nomear cada arquivo pelo fileId
const svg = (id, w, h, altText, extra) => ({ id, typeId: 'figure', kind: 'svg', createdAt: 0,
updatedAt: 0, altText, svg: { fileId: `${id}.svg`, width: w * 10, height: h * 10 }, ...extra });
const row = (...cells) => cells.map((content) => ({ content }));
const head = (...cells) => cells.map((content) => ({ content, isHeader: true }));
const resources = [
svg('cover', PAGE.w, PAGE.h, t({ en: 'A mill wheel on the waterline, its lower half pale '
+ 'under the estuary', es: 'Una rueda de molino en la línea del agua, con la mitad '
+ 'inferior pálida bajo la ría' })),
svg('mill', SECTION.w, SECTION.h, t({
en: 'The mill in section: the pond at high level on the left, the mill house on the dam '
+ 'with its millstones, the horizontal wheel in the vaulted pit, and the estuary on the '
+ 'right below a dashed high-water line',
es: 'El molino en sección: el estanque a nivel alto a la izquierda, la casa del molino sobre '
+ 'la presa con sus muelas, el rodezno en el cárcavo abovedado y la ría a la derecha, bajo '
+ 'una línea discontinua de pleamar' }), {
placement: { position: 'here' },
caption: t({ en: 'Two hours after high water: the pond turns the wheel, and the estuary '
+ 'has fallen below the dashed line.',
es: 'Dos horas tras la pleamar: el estanque mueve el rodezno y la ría ha quedado por debajo '
+ 'de la línea discontinua.' }) }),
{ id: 'hours', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
placement: { position: 'here' },
caption: t({ en: 'Opening hours. Last entry 45 minutes before closing.',
es: 'Horario. Última entrada 45 minutos antes del cierre.' }),
table: { model: { headerRowCount: 1, columnWidths: [1.55, 0.9, 1.55], rows: t({
en: [head('Season', 'Days', 'Hours'),
row('April–June', 'Tue–Sun', '10:00–14:00, 16:00–19:00'),
row('July–August', 'Mon–Sun', '10:00–20:00'),
row('September–March', 'Fri–Sun', '10:30–14:30')],
es: [head('Temporada', 'Días', 'Horario'),
row('Abril–junio', 'Mar.–dom.', '10:00–14:00 y 16:00–19:00'),
row('Julio–agosto', 'Lun.–dom.', '10:00–20:00'),
row('Septiembre–marzo', 'Vie.–dom.', '10:30–14:30')] }) } } },
];
Os dois desenhos são marcação SVG gerada pelo pen e entregue a files sob o svg.fileId dos recursos deles; a tabela são dados, por isso viaja em preset.json com a legenda. O corte e a tabela são postos com position: 'here': o corte no alto do verso, o horário sob o parágrafo que o cita. O folheto define layout.inlineResourceGap: 'above', que mantém o espaço de um recurso na linha só acima dele, e assim o verso cabe num lado da folha: o título depois do corte traz o próprio espaço, e uma linha :::space{lines=0.5} depois da tabela deixa 3,7 mm sob a legenda.
#4 · Manter os rótulos na língua do arquivo
// Hyphenation patterns and the PDF's /Lang.
locale: t({ en: 'en-us', es: 'es' }),
// '{n}' numbers the figures 1, 2, 3: a leaflet has no chapters to number them by. Without
// resourceTypes the reader builds Figure 1.1 or Figura 1.1, in the language of the file.
resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),
Quem abre um arquivo monta os tipos padrão na língua que esse arquivo serve: sem resourceTypes na configuração, o folheto em espanhol imprime Figura 1.1 e Tabla 1.1 onde quer que seja aberto, inclusive no Sandbox em /en/sandbox. O folheto grava os tipos só pelos números: '{n}' tira o número do capítulo, de que um folheto de duas páginas não precisa (tipos de recurso). O mesmo config() define locale, que escolhe os padrões de hifenização do espanhol (compuer-tas no verso) e a língua que o PDF declara.
#5 · Repassar os mesmos bytes
const file = `tide-mill-${LANG}.postext`;
document.getElementById('pt-actions').append(Object.assign(document.createElement('a'), {
href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })), download: file,
textContent: `Download ${file} · ${Math.round(bytes.length / 1024)} KB` }));
// The PDF embeds the faces the bundle carries, and draws the figures from its files.
offerPdf(() => renderToPdf(docs, {
fontProvider: bundleFontProvider(bundle, { decodeWoff2: decompressWoff2 }),
resourceBytes: bundleResourceBytes(bundle),
}), `${RECIPE}-${LANG}.pdf`);
O link oferece os bytes a partir dos quais as páginas foram diagramadas, 132 KB com as fontes. Importado no Sandbox (Livros → Novo → Abrir um arquivo .postext…), o arquivo vira um livro em espanhol ou inglês com a roda como imagem, tirada de thumbnail. O PDF pega as fontes de bundleFontProvider, que devolve a fonte do pacote mais próxima em peso, no mesmo estilo quando houver, e os desenhos de bundleResourceBytes, por isso nenhuma fonte ou imagem é baixada duas vezes (diagramar e renderizar um pacote).
#6 · Desenhar a frente com um só título
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
{ ...caps, color: col('sand') }),
] } } };
A frente é o design do título de capa: o desenho ancorado à página em tamanho total, o texto do título por {titleText}, o chapéu, o olho e a linha de informações vindos dos atributos dele, e um elemento de texto com caixa para a aba da língua. O nível H1 tem span: 'page', de modo que o desenho vai até a borda inferior do papel. Um design de título mantido na coluna é cortado no pé da mancha: o desenho pararia 13 mm acima da borda inferior.
A receita completa
// ═══ Postext Cookbook · Nº 041 · .postext round trip in two languages ════════════
// https://postext.dev/en/cookbook/bundle-round-trip
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { createBundle, openBundle, loadBundleFonts, registerBundleImages, buildBundle,
bundleFontProvider, bundleResourceBytes, defaultResourceTypes, renderPageToCanvas }
from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'bundle-round-trip';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#172130', muted: '#56606c', // text; the colophon
estuary: '#25476a', mud: '#8a6f4d', // the one accent; the wheel's wood in the drawings
sand: '#e9dcc4', foam: '#eef2f3', rule: '#c4ced6', paper: '#ffffff' };
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the estuary blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.estuary })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['DM Sans', 'DM Serif Display', 'Instrument Sans'];
const PAGE = { w: 99, h: 210, top: 12, bottom: 13, side: 10 }; // mm: a DL leaflet, both sides
const [BODY, LEAD] = [9.4, 13.4]; // pt
const WATER = 98; // mm from the top of the cover: where the sand ends and the estuary begins
// #region cover: the front of the leaflet, a heading drawn over one picture
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
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
#Ler um pacote bilíngue
O guia do Postext leva num só arquivo os capítulos, a configuração e as legendas em inglês e espanhol; { locale } escolhe a edição, que abre como doze capítulos em 48 páginas em qualquer das duas línguas, enquanto o link continua oferecendo o arquivo do folheto e o botão de PDF compõe o guia.
-const bundle = await openBundle(bytes);
+const guide = await fetch('https://postext.dev/bundles/postext-guide.postext');
+const bundle = await openBundle(await guide.arrayBuffer(), { locale: LANG });#Numerar as figuras por capítulo
Sem os tipos, quem abre o arquivo os monta na língua dele com a numeração padrão, e as figuras contam a partir do título de capa: Figura 1.1 e Tabla 1.1 na edição espanhola, Figure 1.1 e Table 1.1 na inglesa.
- resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),Erros comuns
- Aqui cada edição é um arquivo próprio. Para levar as duas línguas num só, passe a
createBundleum mapalocalized(Pacotes bilíngues);openBundle(bytes, { locale })então lê qualquer uma das duas edições.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fontes
- DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


