我使用bwip-js来生成条形码,使用pdfkit来生成将显示所述条形码的PDF.

我让bwip-js生成条形码的PNG图像,但它只提供PNG的缓冲区.然后,我使用fs.WriteFile从该缓冲区生成一个PNG(可能做错了这一部分).

无论如何,当我把PNG放到pdf中时,pdfkit给出了一个错误,图像是Uknown image format

同时,如果我在电脑的文件资源管理器中打开保存PNG的目录,我可以很好地打开图像.

我发现this个答案似乎描述了相同的问题,但我没有运气让bwip-js使用.png而不是.png生成PNG

我觉得在获取bwp-js提供的缓冲区并将其转换为PNG文件的过程中,我好像错过了一些东西.

代码:

const PDFDocument = require("pdfkit");
const bwipjs = require("bwip-js");
const fs = require("fs");

function generateCustomerInvoice(data) {
  const id = "12345678"
  bwipjs
    .toBuffer({
      bcid: "code128",
      text: id,
      scale: 3,
      height: 10,
      includetext: true,
      textxalign: "center",
    })
    .then((png) => {
      fs.writeFile("./barcodes/" + id + ".png", png, () => {});
      console.log("Barcode Finished");
    })
    .then(() => {
      const doc = new PDFDocument({ autoFirstPage: false });
      doc.pipe(fs.createWriteStream("./pdfs/customer/" + id + ".pdf"));
      doc.addPage({ size: "A5", margin: 20 });
      doc.lineWidth(1);
      doc.lineCap("butt").moveTo(20, 20).lineTo(399.53, 20).stroke();
      doc.lineCap("butt").moveTo(20, 20).lineTo(20, 575.28).stroke();
      doc.lineCap("butt").moveTo(399.53, 20).lineTo(399.53, 575.28).stroke();
      doc.lineCap("butt").moveTo(20, 575.28).lineTo(399.53, 575.28).stroke();
      doc.fontSize(12).text("Customer Invoice", 40, 40);
      doc.image("./barcodes/" + id + ".png", 40, 40);
      doc.end();
    });
}

推荐答案

您编写的".png"图像部分错误.

Js运行在非阻塞I/O模型上,这意味着它不需要等到读写文件系统等操作完成后才继续下一行代码.这对性能很有好处,但当一个操作依赖于另一个操作的完成时,可能会导致问题.

在您的函数中,您将使用fs.WriteFile()将条形码图像写入磁盘.此方法是异步的-它启动写入过程,然后立即继续,而不是等待文件写入完成.

函数的作用是异步的.

这意味着它启动文件写入过程,然后立即移动到下一行代码,而无需等待文件写入完成.

因此,下一步"fs.createWriteStream()"没有机会读取完成的图像. 因此,此代码将创建正确的PDF文件.

const PDFDocument = require("pdfkit");
const bwipjs = require("bwip-js");
const fs = require("fs");

function generateCustomerInvoice(invoiceData) {
    const id = invoiceData.invoiceNumber;
    const barcodeDir = "./barcodes/";
    const pdfDir = "./pdfs/customer/";

    if (!fs.existsSync(barcodeDir)) {
        fs.mkdirSync(barcodeDir, { recursive: true });
    }

    if (!fs.existsSync(pdfDir)) {
        fs.mkdirSync(pdfDir, { recursive: true });
    }

    bwipjs.toBuffer({
        bcid: "code128",
        text: id,
        scale: 3,
        height: 10,
        includetext: true,
        textxalign: "center",
    })
        .then((png) => {
            return new Promise((resolve, reject) => {
                fs.writeFile("./barcodes/" + id + ".png", png, (err) => {
                    if (err) {
                        console.error("Error writing file:", err);
                        reject(err);
                    } else {
                        console.log("Barcode Finished");
                        resolve();
                    }
                });
            });
        })
        .then(() => {
            const doc = new PDFDocument({ autoFirstPage: false });
            doc.pipe(fs.createWriteStream("./pdfs/customer/" + id + ".pdf"));
            doc.addPage({ size: "A5", margin: 20 });

            doc.fontSize(12).text("Customer Invoice", 40, 30);

            doc.image("./barcodes/" + id + ".png", 40, 60, { width: 150 });

            doc.fontSize(10).text(`Customer Name: ${invoiceData.customerName}`, 40, 130);

            const tableTop = 160;
            doc.fontSize(10);
            doc.text("Description", 40, tableTop);
            doc.text("Quantity", 200, tableTop);
            doc.text("Price", 280, tableTop);
            doc.text("Total", 360, tableTop);

            let verticalPosition = tableTop;
            invoiceData.items.forEach(item => {
                verticalPosition += 20;
                doc.text(item.description, 40, verticalPosition);
                doc.text(item.quantity, 200, verticalPosition);
                doc.text(`$${item.price.toFixed(2)}`, 280, verticalPosition);
                doc.text(`$${(item.quantity * item.price).toFixed(2)}`, 360, verticalPosition);
            });

            doc.end();
        })
        .catch((err) => {
            console.error("Error in PDF generation: ", err);
        });
}

generateCustomerInvoice({
    customerName: "Tom Cruise",
    invoiceNumber: "INV-10001",
    items: [
        { description: "Item 1", quantity: 2, price: 100.00 },
        { description: "Item 2", quantity: 5, price: 50.00 }
    ],
});

Result enter image description here

更多详细信息请参见here

Node.js相关问答推荐

运行JEST测试时找不到模块&q;错误

填充函数在Node.js和MongoDB中不起作用

我需要聚合两个 MongoDB 集合

bcrypt.compare 每次都返回 false

在 getServerSideProps 中使用 EmailProvider 获取 NextAuth 会话会抛出 fs找不到模块

多字段传递获取查询失败

如何删除mongodb中嵌套数组中所有出现的数组元素

NodeJS 后端发布请求将数据作为NULL值发布到 SQL Server 表

当我使用 uuid 代码意外崩溃,然后工作正常?

如何申请在NextJS上下载文件的许可?

我们如何或可以通过 npm 和 Meteor 使用 node 模块?

在 ExpressJS 中将变量传递给 JavaScript

npm publish 导致'错误:EPERM:不允许操作,取消链接...',errno -4048

Nodejs续集批量更新

Puppeteer:如何提交表单?

node.js 中存储的模块变量在什么范围内?

如何从 findOneAndUpdate 方法中获取更新的文档?

nodeJS - 如何使用 express 创建和读取会话

当我try 向我的 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证

`return function *(){...}` 是什么意思?