本文へスキップ
レシピ番号41

レシピ集 · 第10章 · 出力と組み込み

2言語の.postextの往復

両面のDLリーフレットをコードで.postextファイルに書き出し、そのバイト列から組み直します。各版が持つ書体、図、キャプションのラベルもいっしょです。

このページの内容

1ページ(全2ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり99 × 210 mm
  • 1段
  • DM Sans 9.4/13.4
  • DM Serif Display
  • Instrument Sans
  • 2ページ
  • レベル
  • Postext 1.57.1
  • 組版時間68 ms
  • コード178行

かんたんな説明

古い潮力水車小屋を紹介する両面のリーフレットを、英語とスペイン語で作ります。文書をフォントや画像といっしょに1つのファイルに保存し、そのファイルから同じページを取り戻す方法を示します。

できあがり

架空の入り江にある潮力水車小屋の来館者用DLリーフレット(99 × 210 mm)の両面です。おもて面は1枚の画像です。水際に水車があり、上半分は砂の上、下半分は青い水の下で淡く描かれます。表題は50 ptのDM Serif Displayイタリック、青いタブには版の言語(ENまたはES)が入ります。裏面は水車小屋の断面図で始まり、両端そろえのDM Sansの本文、青い見出し行の付いた開館時間の表、Instrument Sansのキャプション、奥付、発行者名の入った青い帯と続きます。各版は.postextファイルに書き出され、ここに載せたページはすべて、そのファイルのバイト列から、ファイルに入った書体と図で組んだものです。

このレシピが答える質問

  • .postextファイルを開き、同梱のフォント・画像・設定で描画するには?
  • コードから.postextバンドルを作り、文書をSandboxやほかのプログラムに渡すには?
  • 1つのプロジェクトから、同じ本を2つの言語で出版するには?
  • 「図」や「表」のラベルを文書の言語で表示するには?

手短な答え

script.js · 294〜310行コード全体で見る
// 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

材料

種類
DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · 版を書き出し、バイト列だけを読み戻す

script.js · 294〜310行コード全体で見る
// 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は章、設定、リソース、そしてそれらが参照するすべてのファイルをzipにまとめます。openBundleが受け取るのはそのバイト列だけです。書体はloadBundleFontsから、図はregisterBundleImagesから、デザインはbundle.configから取ります。filesに入れ忘れた書体はブラウザーの代替フォントで印字され、入れ忘れた図は警告とともに省かれ、その参照は(?)と印字されます。zipの中では各fileIdがパスになり(mill.svgはresources/mill.svgになります)、openBundleが返すリソースとcustomFontsはすでに新しい名前を使っています(バンドルを開く)。

#2 · 書体をファイルに入れる

script.js · 277〜289行コード全体で見る
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())];
  }))));

バンドルに書体が入るのは、customFontsがその書体を指定し、filesにそのバリエーションのfileIdでバイト列が入っているときです。createBundleはDM Sans 400をfonts/dm-sans-400-normal.woff2として格納します。CodePenのサンプルはFontsourceから7つのwoff2ファイルをダウンロードしますが、どれも登録しません。buildBundleが行を測る前にloadBundleFontsがバンドル内の複製をdocument.fontsに加え、PDFも同じ7ファイルから書体を取ります。

#3 · どのファイルもfileIdで名付ける

script.js · 234〜267行コード全体で見る
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')] }) } } },
];

2点の図はCodePenのサンプルが生成するSVGマークアップで、それぞれのリソースのsvg.fileIdの名前でfilesに渡します。表はデータなので、キャプションといっしょにpreset.jsonに入って運ばれます。断面図と表はposition: 'here'で配置します。断面図は裏面の先頭に、開館時間の表はそれを引用する段落の下に置かれます。このリーフレットはlayout.inlineResourceGap: 'above'を設定し、行内のリソースの間隔を上側だけにして、裏面を1面に収めています。断面図のあとの見出しは自分の間隔を取り、表のあとの:::space{lines=0.5}の行がキャプションの下に3.7 mmをあけます。

#4 · ラベルをファイルの言語のままにする

script.js · 55〜59行コード全体で見る
  // 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}' })),

ファイルを開く側は、組み込みの種類をそのファイルの言語で組み立てます。設定にresourceTypesがなくても、スペイン語のリーフレットは、/en/sandboxのSandboxを含めてどこで開いてもFigura 1.1とTabla 1.1を印字します。このリーフレットが種類を書き込むのは番号のためだけです。'{n}'は章番号を落とします。2ページのリーフレットに章番号は不要です(リソースの種類)。同じconfig()でlocaleも設定し、これでスペイン語のハイフネーションパターン(裏面のcompuer-tas)と、PDFが宣言する言語が決まります。

#5 · 同じバイト列を渡す

script.js · 316〜324行コード全体で見る
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`);

リンクからは、ページを組んだのと同じbytes、フォント込みで132 KBのファイルを取得できます。Sandboxで読み込むと(本 › 新規 › .postextファイルを開く…)、ファイルはスペイン語または英語の本になり、thumbnailから取った水車の画像がその本の画像になります。PDFは書体をbundleFontProviderから取ります。これはバンドル内でウェイトが最も近い書体を、同じスタイルがあればそのスタイルで返します。図はbundleResourceBytesから取るので、フォントも画像も2度ダウンロードされることはありません(バンドルを組んで描画する)。

#6 · おもて面を見出しひとつで描く

script.js · 28〜50行コード全体で見る
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') }),
] } } };

おもて面は表紙用の見出しのデザインです。図を原寸でページに固定し、見出しの文字は{titleText}で、キッカー、リード文、案内の1行は見出しの属性から取り、言語のタブはボックス付きのテキスト要素で描きます。H1のレベルはspan: 'page'なので、図は用紙の下端まで届きます。見出しのデザインを段の中に置いたままにすると、版面の下端で切られ、図は下端の13 mm手前で止まります。

レシピの全体

Sandbox
// ═══ 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'),

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#2言語のバンドルを読む

Postextガイドは、英語とスペイン語の章、設定、キャプションを1つのファイルに収めています。{ locale }で版を選ぶと、どちらの言語でも48ページ、12章として開きます。このときリンクから取得できるのはリーフレットのファイルのままで、PDFボタンはガイドを組みます。

-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 });

#図を章ごとに数える

種類を指定しないと、開く側がファイルの言語と既定の番号で種類を組み立て、図は表紙の見出しから数えられます。スペイン語版はFigura 1.1とTabla 1.1、英語版はFigure 1.1とTable 1.1を印字します。

-  resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),

よくあるつまずき

  • ここでは版ごとに1つのファイルを書き出しています。2つの言語を1つのファイルに入れるには、createBundleにlocalizedのマップを渡します(多言語のバンドル)。そうすればopenBundle(bytes, { locale })でどちらの版も読めます。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
SandboxPDF