【发布时间】:2019-08-02 08:45:07
【问题描述】:
所以我正在使用 node.js 中的库 pdf-lib 将文本嵌入到 pdf 中。我想要做的是将名称嵌入pdf中的白框,并根据字符串的长度将它们对齐到中心。 firstPage.drawText 是正确对齐文本的部分。我需要的是一种根据字符串长度对齐文本的算法。这是我尝试过的,提前谢谢
async function loadandModPDF(name, gender) {
// Load a PDFDocument from the existing PDF bytes
const pdfDoc = await PDFDocument.load(existingPdfBytes);
pdfDoc.registerFontkit(fontkit);
const contName = await pdfDoc.embedFont(nameBold);
// Get the first page of the document
const pages = pdfDoc.getPages();
const firstPage = pages[0];
const textSize = 16;
try {
textWidth = contName.widthOfTextAtSize(name, textSize);
}
catch (e) {
console.log(e);
}
// Get the width and height of the first page
const { width, height } = firstPage.getSize();
// Draw a string of text diagonally across the first page
firstPage.drawText("John Doe" , {
x: (width - textWidth) / 3.1,
y: height - (textSize * 26),
size: textSize,
font: contName,
color: rgb(0, 0, 0),
rotate: degrees(0),
});
【问题讨论】:
标签: javascript node.js pdf