Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

PDF-LIB SingleLineTextLayout example

Writer Olivia Zamora

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) }
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.