【问题标题】:Align text according to length of string根据字符串长度对齐文本
【发布时间】: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


    【解决方案1】:

    我一直在使用pdfkit。它根据字符串的长度自动对齐文本

    import * as PDFDocument from 'pdfkit'
    import getStream from 'get-stream'
    
    const pdf = {
      createPdf: async (text: string) => {
        const doc = new PDFDocument()
        doc.fontSize(10).text(text, 50, 50)
        doc.end()
    
        const data = await getStream.buffer(doc)
        let b64 = Buffer.from(data).toString('base64')
        return b64
      }
    }
    
    export default pdf
    
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2018-04-11
      • 2019-07-15
      • 2012-01-19
      • 2020-05-14
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多