node批量生成PDF并生成压缩包下载

2,042 阅读1分钟

最近有需求,将一批数据填充到特定的模板,生成PDF,并把该批次的PDF生成压缩包下载。主要用html-pdf这个库,将html模板生成PDF,然后通过compressing压缩文件夹。

首先,读取excel数据(注意:excel表字段的顺序不能修改,不然最终数据读取会出错),并返回去除表头的数组

const xlsx = require('node-xlsx');

const readExcel = (ctx, name) => {
    const file = ctx.request.files[name],
	filePath = file.path,
	excel = xlsx.parse(filePath);

    if(!filePath){
	logger.error('文件路径错误,请上传文件!');
	return;
    }

    let sheet = excel[0].data;
    sheet.shift();

    return sheet;
}

得到excel数组后,遍历数组,通过正则匹配html模板中自己设置的字符串,替换成对应的数据

const pdf = require('html-pdf');
const fs = require('fs');

// data 为每一行的excel数据
const createPdf = (data) => {
    let html = fs.readFileSync('./src/views/index.html', 'utf8');
    const reg = [
        {
            rules: /__name__/g,
            match: data[0]
        },
        {
            rules: /__idNumber__/g,
            match: data[1]
        }
    ]              // 此处匹配省略多个字段
    
    reg.map((item, index) => {
	html = html.replace(item.rules, item.match);
    })
    
    // date 根据每天导入的数据将pdf生成到对应日期的文件夹,对应日期文件夹应先创建(fs.mkdir())
    pdf.create(html).toFile(`./pdf/${date}/${data[0]}.pdf`, (err, res) => {
	if(err){
	    logger.error(err);
	    return;
	}

	logger.info(res);
    })
}

html模板部分代码,html我用了nunjucks模板,因为有些页面的数据需要从后端传递

<p><span>__name__</span>(先生/女士):身份证号:<span>__idNumber__</span></p>

生成pdf后压缩下载,用到了koa-send这个静态文件服务中间件

const koaSend = require('koa-send');
const compressing = require('compressing');

const compressDir = async (dirName) => {
    let result = compressing.zip.compressDir(dirName, `./pdf/${date}.zip`);
    return result;
}

/*
    页面下载
    dirName: `./pdf/${date}`文件夹
    zipPath: `./pdf/${date}.zip`
*/
router.get('/download', async (ctx, next) => {
    await compressDir(dirName);

    ctx.attachment(zipPath);    // 以附件形式下载
    await koaSend(ctx, zipPath)
})

然后点击页面下载按钮就可以下载对应的压缩包了。