我需要右对齐我使用 PDF-LIB 创建的 PDF 中的一些文本,我在 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 文档不包含任何代码示例。
你可以使用
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)
}
}