javascript PDF-LIB SingleLineTextLayout示例

yks3o0rb  于 4个月前  发布在  Java
关注(0)|答案(2)|浏览(61)

我需要右对齐一些文本在PDF我创建与PDF-LIB,我看到在API文档有一个功能
具有左对齐、右对齐和居中对齐选项的SingleLineTextLayout
https://pdf-lib.js.org/docs/api/interfaces/singlelinetextlayout
https://pdf-lib.js.org/docs/api/interfaces/layoutsinglelinetextoptions
然而,我在这里以及Google和Bing上搜索过,没有找到任何如何使用此函数的示例。PDF-LIB的API文档不包括任何代码示例。

cl25kdpy

cl25kdpy1#

丹尼尔的回答很有帮助。但有两行需要更正:

let centerText = setTextCenter(pages[0], font, fontSize)

let rightText = setTextRight(pages[0], font, fontSize)

字符串

iugsix8n

iugsix8n2#

你可以这样使用widthOfTextAtSize字体属性:

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

字符串

相关问题