To use custom fonts, you must register a fontkit implementation (such as @cantoo/fontkit) using pdfDoc.registerFontkit(fontkit). Once registered, you can use pdfDoc.embedFont(fontBytes) to embed the font.
After embedding, you can use the font object to measure text dimensions:
font.widthOfTextAtSize(text, size): Returns the width of the text.font.heightAtSize(size): Returns the height of the text at the given size.
This is useful for calculating bounding boxes for drawing rectangles around text.
import { PDFDocument, rgb } from 'pdf-lib'
import fontkit from '@cantoo/fontkit'
const fontBytes = ...
const pdfDoc = await PDFDocument.create()
// Register fontkit
pdfDoc.registerFontkit(fontkit)
// Embed custom font
const customFont = await pdfDoc.embedFont(fontBytes)
const page = pdfDoc.addPage()
const text = 'This is text in an embedded font!'
const textSize = 35
// Measure text
const textWidth = customFont.widthOfTextAtSize(text, textSize)
const textHeight = customFont.heightAtSize(textSize)
page.drawText(text, {
x: 40,
y: 450,
size: textSize,
font: customFont,
color: rgb(0, 0.53, 0.71),
})
// Draw a box around the text using measured dimensions
page.drawRectangle({
x: 40,
y: 450,
width: textWidth,
height: textHeight,
borderColor: rgb(1, 0, 0),
borderWidth: 1.5,
})
const pdfBytes = await pdfDoc.save()