nodejs 根据Excel数据批量生成条形码标签

依赖的npm包   :  JsBarcode,pdfkit ,svg-to-pdfkit ,xlsx

excel表格表头包含 : SKU ,name, barcode

根据Excel里的数据大批量生成条形码标签, pdf矢量格式, 一个标签一个文件

代码:

const fs = require('fs'),
    JsBarcode = require('JsBarcode'),
    PDFDocument = require('pdfkit'),
    SVGtoPDF = require('svg-to-pdfkit'),
    XLSX = require('xlsx');
const { DOMImplementation, XMLSerializer } = require('xmldom');
 
function bagLabel(dataline) {
    //新建pdf   默认分辨率 72dpi
    var doc = new PDFDocument({
        size: [153, 113], 
        margins: {
            top: 6,
            bottom: 3,
            left: 2,
            right: 2
        }
    }),
        stream = fs.createWriteStream(`${dataline.SKU}-${dataline.name}-${dataline.barcode}标签.pdf`);
    //插入文本(必须指定中文字体路径)
    doc.font('c:/Windows/Fonts/simhei.ttf').fontSize(14).text(dataline.name, { align: 'center', width: 149 });
    //生成条码
    const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
    const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    JsBarcode(svgNode, dataline.barcode, {
        xmlDocument: document,
        format: "CODE128",
        width: 2,
        height: 100,
        fontSize:12,
        margin:1
    });
    //插入条码
    SVGtoPDF(doc, svgNode, 15, 22);
    //写入文件并关闭
    stream.on('finish', function () {
        console.log('保存标签');
    });
    doc.pipe(stream);
    doc.end();
}
//读取Excel
var workbook = XLSX.readFile('barcodes.xlsx');
var worksheet = workbook.Sheets['Sheet1'];
var datalist = XLSX.utils.sheet_to_json(worksheet);
//遍历数据
datalist.forEach(function(d){
    bagLabel(d);
});

 

上一篇:微信公众号文章中如何添加及上传pdf、doc、xls等文件给粉丝下载


下一篇:springcloud-Dashboard 流量监控 (九)