【问题标题】:How to center continued text using PdfKit?如何使用 PdfKit 将连续文本居中?
【发布时间】:2023-02-02 07:43:40
【问题描述】:

我有这段代码:

const PDFDocument = require("pdfkit");
const QRCode = require("qrcode");
const fs = require("fs");

const exec = async () => {
  const doc = new PDFDocument({ layout: "landscape" });
  doc.pipe(fs.createWriteStream("output.pdf"));

  for (let pageNumber = 1; pageNumber <= 1000; pageNumber++) {
    const url = await QRCode.toDataURL("I am a url!");

    doc
      .image(url, 10, 100, {
        width: 420,
        height: 420,
        align: "center",
        valign: "center",
      })

    doc
      .font("Helvetica")
      .fontSize(50)
      .fillColor("#000")
      .text(`Item `, 465, 200, { continued: true })
      .fontSize(55)
      .font("Courier-Bold")
      .fillColor("#1b83c5")
      .text(`${pageNumber}`);

    doc
      .font("Helvetica-Bold")
      .fontSize(40)
      .fillColor("#000")
      .text("Order and Pay", 420, 320);

    doc.addPage();
  }

  doc.end();
};

exec();

这会产生这样的东西:

它看起来居中,但是随着页面的增加它将不再居中,因为数字是固定的。

我在文档中看到有一个 align 属性,但文档没有解释如何处理连续文本。

任何工作示例?

【问题讨论】:

    标签: node.js pdfkit


    【解决方案1】:

    也许有点晚了,但我找到了解决同样问题的解决方案:

    首先,您需要创建一个常量,其中包含您希望文本居中的容器的宽度:(您必须计算或发明这个值,但这很容易做到)

    const containerWidth = 100 // as an example
    

    然后,您需要创建一个变量,其中包含一个纯字符串,该字符串包含您想要居中的所有文本,在您的示例中:

    var appendedText = `Item ${pageNumber}`
    

    最后,需要使用pdf-kit的函数widthOfString,在文档中添加如下文字:

    const xOffset = 465 // The original X offset value
    doc
    .text(`Item `, xOffset + (containerWidth / 2) - (doc.widthOfString(appendedText) / 2), 200, { continued: true })
    .text(`${pageNumber}`);
    

    【讨论】:

      猜你喜欢
      • 2021-04-11
      • 2013-01-10
      • 2016-05-05
      • 2015-04-08
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 2013-02-28
      • 2011-09-24
      相关资源
      最近更新 更多