我正在使用https://github.com/devongovett/pdfkit生成PDF文件,我可以使用
之类的东西app.get('/get-pdf', (req, res) => {
const doc = new PDFDocument();
const filename = 'my_pdf.pdf';
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
const content = "Some content";
doc.y = 300;
doc.text(content, 50, 50);
doc.pipe(res);
doc.end();
});
但我也想生成一个UPC-A条形码:
我找到了可以从12位代码生成此类条形码的库https://github.com/lindell/JsBarcode。但是,似乎该库主要用于客户端。
我想用这样的条形码生成PDF,但我不知道该怎么做,或者JsBarcode对于这种单一类型的条形码来说不是太复杂。
正如评论中所建议的,我确实尝试使用UPC-A字体生成条形码:
app.get('/get-pdf', (req, res) => {
const doc = new PDFDocument();
const filename = 'my_pdf.pdf';
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
doc.font('/fonts/UPC-A.ttf').fontSize(50).text('012345678905');
doc.pipe(res);
doc.end();
});
我从中获得
看起来不错,但它看起来并不像普通的UPC-A条形码。
答案 0 :(得分:0)
我从未使用JsBarcode
因此我无法帮助您使用此lib。但逻辑是获取代码栏的Base64字符串并将其添加到您的PDF文件中。
我使用npm模块rescode
在我的项目中执行此操作。下面的代码生成一个ean8代码栏并在PDF中添加此图像,它可以正常工作。
codes = require('rescode')
codes.loadModules(['ean8'])
dataEan8 = codes.create('ean8', '12345678')
doc.image(dataEan8, 10, 10, height:30, width:130)
答案 1 :(得分:0)
从Google字体:https://fonts.google.com/?query=barcode(根据您的要求)下载ttf
字体文件以获取条形码
在我的情况下,我只希望没有文本的条形码,所以我使用https://fonts.google.com/specimen/Libre+Barcode+39
将此ttf字体文件放到public/fonts
侧文件夹中
doc.font(__dirname+ "/../../public/fonts/LibreBarcode39-Regular.ttf").fontSize(20).text(012345678905);
它将在下面的条形码中生成:
如果您想在文本中使用条形码,请使用以下字体:https://fonts.google.com/specimen/Libre+Barcode+39+Text
答案 2 :(得分:0)
使用正确的字体文件(在本例中为您的 UPC-A.ttf
)是不够的,还需要正确编码数字。
使用此 TTF 文件,以下代码有效(假设 barcode
已经是一个包含正确校验位的 12 位字符串 - 如果不是,您可以使用类似 npm 模块 cdigit
的东西先计算校验位):
const barcodeEncoded =
// First digit including leftmost bar
String.fromCharCode(Number(barcode[0]) + 0x50) +
// Regular digits in the left half
barcode.slice(1, 6) +
// Middle bar
'p' +
// Differently encoded digits in the right half
barcode.slice(6, 11).split('').map(x => String.fromCharCode(Number(x) + 0x40)).join('') +
// Last digit including rightmost bar
String.fromCharCode(Number(barcode[11]) + 0x60)
这样,012345678905
就会变成 P12345pFGHI@e
,这将是具有这种字体的有效 UPC-A 条码。
有关详细信息,请查看 readme of the font 和此 article about how such barcode is constructed。
答案 3 :(得分:0)
我使用 JSBarcode 和 Canvas 在 pdf 中生成条码。
您需要为此安装 JSBarcode:
npm install jsbarcode
用于在 PDF 中生成条码的代码:
var canvas = document.createElement("canvas");
JsBarcode(canvas, "3000001", {
format: "ean8", height: 20,
displayValue: false
});
doc.image(canvas.toDataURL(), 10, 10, height:30, width:130);