Skip to content

zeropdf v1.3.0


zeropdf / TextShaper

Interface: TextShaper

Defined in: src/internal/text-shaper.ts:83

Interface for pluggable text shaping engines.

The default shaper handles basic Latin ligatures and Arabic joining forms. For complex scripts (Devanagari, Thai, Khmer, Myanmar, etc.), you can provide a custom shaper that uses HarfBuzz, fontkit, or another shaping engine to produce correctly positioned glyphs.

Creating a custom shaper

Implement the shape method and pass your shaper via DocumentOptions.textShaper or PdfDocument.setTextShaper:

Example

ts
import { createDocument, TextShaper, ShapedGlyph } from "@criston/zeropdf";

// Example custom shaper using harfbuzzjs:
//
// async function createHarfBuzzShaper(harfbuzzInstance: any): TextShaper {
//   return {
//     shape(text, font, direction, script) {
//       const buffer = harfbuzzInstance.createBuffer();
//       buffer.addText(text);
//       buffer.setDirection(direction === "rtl" ? "rtl" : "ltr");
//       if (script) buffer.setScript(script);
//       const hbFont = createHarfBuzzFontFromParsedFont(font, harfbuzzInstance);
//       harfbuzzInstance.shape(hbFont, buffer);
//       const jsonResult = buffer.json();
//       buffer.destroy();
//       return jsonResult.map((g: any) => ({
//         glyphId: g.g,
//         xOffset: g.dx,
//         yOffset: g.dy,
//         xAdvance: g.ax,
//         yAdvance: g.ay,
//       }));
//     }
//   };
// }

// For fontkit-based shaping:
//
// async function createFontkitShaper(fontData: Uint8Array): TextShaper {
//   const fontkit = await import("fontkit");
//   const fkFont = fontkit.create(fontData);
//   return {
//     shape(text, font, direction) {
//       const run = fkFont.layout(text);
//       return run.glyphs.map((g: any) => ({
//         glyphId: g.id,
//         xOffset: g.xOffset ?? 0,
//         yOffset: g.yOffset ?? 0,
//         xAdvance: g.advanceWidth ?? 0,
//         yAdvance: g.advanceHeight ?? 0,
//       }));
//     }
//   };
// }

const doc = createDocument({ textShaper: myCustomShaper });

Methods

shape()

ts
shape(
   text, 
   font, 
   direction, 
   script?): ShapedGlyph[];

Defined in: src/internal/text-shaper.ts:93

Shapes a text string into an array of positioned glyphs.

Parameters

ParameterTypeDescription
textstringThe text string to shape.
fontParsedTrueTypeFontThe parsed TrueType/OpenType font.
direction"ltr" | "rtl"The text direction ("ltr" or "rtl").
script?stringOptional 4-character OpenType script tag (e.g. "deva", "arab", "thai").

Returns

ShapedGlyph[]

An array of shaped glyphs with positions and advances.

Released under the ISC license.