(text: string, font: FormFont)
| 703 | * Encode text for use in a PDF content stream with the given font. |
| 704 | */ |
| 705 | export 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. |
no test coverage detected