需求
之前我已经了解过如何在pdf模板中填写字段了
nodejs根据pdf模板填入中文数据并生成新的pdf文件 https://blog.csdn.net/ArmadaDK/article/details/132456324
https://blog.csdn.net/ArmadaDK/article/details/132456324
但是当我具体使用的时候,我发现我的模板里面有表格,表格的长度是不固定的,所以需要动态生成一个表格,就要在原方案生成的pdf后面自己画上表格,可以在pdflib的官网上看到一些例子PDF-LIB · Create and modify PDF documents in any JavaScript environment.
具体代码
// 创建一个新页面
      const currentPage = pdfDoc.addPage([pdfWidth, pdfHeight]);用addpage创建一页,并将这页保存为变量方便后续进行操作。
// 绘制表格行数据
      for (let i = startRow; i < endRow; i++) {
        const rowData = arr[i];
        const y = pdfHeight - 100 - (i % rowsPerPage) * cellHeight;
        currentPage.drawRectangle({
          // 每行一个长方形
          x: 50,
          y, // 手动垂直居中
          width: tableWidth,
          height: cellHeight,
          borderColor: rgb(0, 0, 0),
        });
        let idx = 0;
        for (let key in rowData) {
          currentPage.drawText(rowData[key], {
            // 填入文字
            x: 50 + idx * cellWidth + 10,
            y: y + 5,
            size: fontSize,
            font,
          });
          currentPage.drawLine({
            // 竖线
            start: { x: 50 + idx * cellWidth, y },
            end: { x: 50 + idx * cellWidth, y: y + cellHeight },
            thickness: 1,
          });
          idx++;
        }
      }drawText('文字内容',{文字的一些options(注意这里的坐标是左下角)})
drawLine({start:{起点坐标},end:{终点坐标},thickness: 粗细})
这时候发现如果文字是中文的话会出现乱码,就需要引入中文字体,但和上篇的引入方法不一样,这次不能用那个update,而是使用setfont,直接对整个currentPage字体进行设置,如下代码所示:
  // 设置字体
  const fontBytes = await fs.promises.readFile(
    "xxxx.ttf"
  );
  pdfDoc.registerFontkit(fontkit);
  let font = await pdfDoc.embedFont(fontBytes);
。。。
      // 每次创建一个新页面就要设置font
      const currentPage = pdfDoc.addPage([pdfWidth, pdfHeight]);
      currentPage.setFont(font);





![[Linux入门]---进程的概念](https://img-blog.csdnimg.cn/f00dee03fc7945da928cbd7bbc175ed2.png)









![计算机视觉与深度学习-经典网络解析-GoogLeNet-[北邮鲁鹏]](https://img-blog.csdnimg.cn/ee6b62d419af4e99bcbba943cab449c6.png)

