我使用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();
});
}