import * as fontkit from 'fontkit'; import type { Font as FontKitFont } from 'fontkit'; import { b64toUint8Array, mm2pt, pt2mm, pt2px, Font, getFallbackFontName, getDefaultFont, DEFAULT_FONT_NAME, } from '@pdfme/common'; import { Buffer } from 'buffer'; import type { TextSchema, FontWidthCalcValues } from './types.js'; import { DEFAULT_FONT_SIZE, DEFAULT_CHARACTER_SPACING, DEFAULT_LINE_HEIGHT, FONT_SIZE_ADJUSTMENT, DEFAULT_DYNAMIC_FIT, DYNAMIC_FIT_HORIZONTAL, DYNAMIC_FIT_VERTICAL, VERTICAL_ALIGN_TOP, LINE_END_FORBIDDEN_CHARS, LINE_START_FORBIDDEN_CHARS, } from './constants.js'; export const getBrowserVerticalFontAdjustments = ( fontKitFont: FontKitFont, fontSize: number, lineHeight: number, verticalAlignment: string, ) => { const { ascent, descent, unitsPerEm } = fontKitFont; // Fonts have a designed line height that the browser renders when using `line-height: normal` const fontBaseLineHeight = (ascent - descent) / unitsPerEm; // For vertical alignment top // To achieve consistent positioning between browser and PDF, we apply the difference between // the font's actual height and the font size in pixels. // Browsers middle the font within this height, so we only need half of it to apply to the top. // This means the font renders a bit lower in the browser, but achieves PDF alignment const topAdjustment = (fontBaseLineHeight * fontSize - fontSize) / 2; if (verticalAlignment === VERTICAL_ALIGN_TOP) { return { topAdj: pt2px(topAdjustment), bottomAdj: 0 }; } // For vertical alignment bottom and middle // When browsers render text in a non-form element (such as a
), some of the text may be // lowered below and outside the containing element if the line height used is less than // the base line-height of the font. // This behaviour does not happen in a