Calculate Dynamic Font Size using Fontkit

This commit is contained in:
steffancarrington
2023-05-23 10:20:41 +01:00
parent 8c43348353
commit 26a129f4db
3 changed files with 26 additions and 5 deletions

View File

@@ -46,8 +46,8 @@
"prune": "ts-prune src"
},
"dependencies": {
"zod": "^3.20.2",
"fontkit": "^2.0.2"
"fontkit": "^2.0.2",
"zod": "^3.20.2"
},
"jest": {
"resolver": "ts-jest-resolver",

View File

@@ -53,8 +53,6 @@ export const calculateDynamicFontSize: DynamicFontSize = async (activeSchema, fo
let textContent;
let schemaFontSize = baseFontSizeInPixels;
let dynamicFontSize = baseFontSizeInPixels;
// Detect if multiline text and get the width of each line in mm but only return the largest width
const textContentRows = data.split('\n');
const textContentRowMaxWidth = (

View File

@@ -1,4 +1,5 @@
import { PDFFont } from '@pdfme/pdf-lib';
import * as fontkit from 'fontkit';
import { calculateCharacterSpacing } from './calculateCharacterSpacing';
import { DEFAULT_PT_TO_MM_RATIO } from '../constants';
@@ -7,6 +8,7 @@ type CalculateTextWidthInMm = (
textFontSize: number,
textFontFamily: PDFFont,
textCharacterSpacing: number
// textFontData?: ArrayBufferLike
) => number;
export const calculateTextWidthInMm: CalculateTextWidthInMm = (
@@ -14,10 +16,31 @@ export const calculateTextWidthInMm: CalculateTextWidthInMm = (
textFontSize,
textFontFamily,
textCharacterSpacing
// textFontData
) => {
const characterSpacingWidth = calculateCharacterSpacing(textContent, textCharacterSpacing);
const textContentWidthInPt = textFontFamily.widthOfTextAtSize(textContent, textFontSize) + characterSpacingWidth;
const textContentWidthInPt =
textFontFamily.widthOfTextAtSize(textContent, textFontSize) + characterSpacingWidth;
const textContentWidthInMm = textContentWidthInPt * DEFAULT_PT_TO_MM_RATIO;
// Calculate Text Width using Fontkit
// if (textFontData) {
// let font = fontkit.create(new Uint8Array(textFontData));
// console.log(font, font.familyName);
// // Set the font size
// const fontSizeTest = 16;
// const fontText = 'Hello, World! Hello, World!';
// let widthTest = 0;
// for (let character of fontText) {
// const glyph = font.glyphForCodePoint(character.codePointAt(0));
// widthTest += (glyph.advanceWidth / font.unitsPerEm) * fontSizeTest;
// }
// console.log(`Width of "${fontText}": ${widthTest} in pts`);
// }
return textContentWidthInMm;
};