Pdf-Lib Singlelinetextlayout Example
I Am Needing to Right Align Some Text in a Pdf I Am Creating with Pdf-Lib, and I See in the Api Docs There Is a Function Singlelinetextlayout with Left, Right...
I am needing to right align some text in a PDF I am creating with PDF-LIB, and I see in the API docs there is a function
SingleLineTextLayout with left, right, and center for alignment options
However, I have searched here and on Google and Bing and have not found any examples of how to use this function. The API documentation for PDF-LIB does not include any code examples.
1 Answer
you can do it using widthOfTextAtSize font property like this:
const pdfDoc = await PDFDocument.load(file)
const pages = pdfDoc.getPages()
const font = await pdfDoc.embedFont(StandardFonts.TimesRoman)
const fontSize = 10
let centerText = setPageTextCenter(pages[0], font, fontSize)
centerText('This text is center aligned', xPos, yPos)
let rightText = setPageTextCenter(pages[0], font, fontSize)
rightText('this text is right aligned', xPos, yPos)
const setTextCenter = (page, font, size) => {
return (text, x, y) => {
const widthText = font.widthOfTextAtSize(text, size)
const props = {
x: x - widthText / 2,
y: y,
size,
font,
}
page.drawText(text, props)
}
}
const setTextRight = (page, font, size) => {
return (text, x, y) => {
const widthText = font.widthOfTextAtSize(text, size)
const props = {
x: x - widthText,
y: y,
size,
font,
}
page.drawText(text, props)
}
}