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, 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

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.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest