MCPcopy Create free account
hub / github.com/LibPDF-js/core / encodeTextForFont

Function encodeTextForFont

src/document/forms/appearance-utils.ts:705–734  ·  view source on GitHub ↗
(text: string, font: FormFont)

Source from the content-addressed store, hash-verified

703 * Encode text for use in a PDF content stream with the given font.
704 */
705export function encodeTextForFont(text: string, font: FormFont): PdfString {
706 if (isEmbeddedFont(font)) {
707 font.markUsedInForm();
708
709 if (!font.canEncode(text)) {
710 const unencodable = font.getUnencodableCharacters(text);
711 const firstBad = unencodable[0];
712
713 throw new Error(
714 `Font cannot encode character '${firstBad}' (U+${firstBad.codePointAt(0)?.toString(16).toUpperCase().padStart(4, "0")})`,
715 );
716 }
717
718 const gids = font.encodeTextToGids(text);
719 const bytes = new Uint8Array(gids.length * 2);
720
721 for (let i = 0; i < gids.length; i++) {
722 bytes[i * 2] = (gids[i] >> 8) & 0xff;
723 bytes[i * 2 + 1] = gids[i] & 0xff;
724 }
725
726 return PdfString.fromBytes(bytes);
727 }
728
729 if (isExistingFont(font) && font.isCIDFont) {
730 return PdfString.fromBytes(font.encodeTextToBytes(text));
731 }
732
733 return PdfString.fromString(text);
734}
735
736/**
737 * Generate color operators for text rendering.

Callers 6

generateCombAppearanceFunction · 0.90
generateButtonAppearanceFunction · 0.90

Calls 10

isEmbeddedFontFunction · 0.90
isExistingFontFunction · 0.90
markUsedInFormMethod · 0.80
encodeTextToGidsMethod · 0.80
encodeTextToBytesMethod · 0.80
canEncodeMethod · 0.65
toStringMethod · 0.45
fromBytesMethod · 0.45
fromStringMethod · 0.45

Tested by

no test coverage detected