0

我正在尝试打印多个 jsPDF.HTML(...) 的结果。它们中的每一个都在同一 div 内的列表的不同分页中运行。该 div 的 PDF 转换多次显示第一页,即使我可以在执行每个 jsPDF.HTML(...) 之前在 UI 中看到其中的项目发生变化。

是否有解决方案或至少解释为什么会发生这种情况?

  async printReceipt() {
    console.log('getting the number of pages in the pagination');
    var lenArr = new Array(Math.ceil(this.receiptItems.length / 10));
    var doc = new jsPDF('p', 'pt', [496, 702]);
    var arrayBuffer: ArrayBuffer[] = [];
    var fileURL;
    console.log('creatting main doc');
    for (let index = 0; index < lenArr.length; index++) {
      console.log('Changing pagination to:', index + 1);
      this.page = index + 1;
      console.log('Converting page:', index + 1);
      await new Promise<void>(async (resolve, reject) => {
        doc.html(document.getElementById('receipt'), {
          callback: async (res) => {
            console.log('Adding page to buffer, page:', index + 1);
            arrayBuffer.push(res.output('arraybuffer'));
            if (lenArr.length - 1 == index) {
              console.log('Printing');
              await this.mergePdfs(arrayBuffer);
            }
            resolve();
          },
        });
      });
    }
  }

日志顺序:

在此处输入图像描述

4

1 回答 1

0

我通过将 jsPDF 对象的声明移动到 Promise 中并在页面更改和 Promise 之间添加超时来解决了这个问题。

  async printReceipt() {
    console.log('getting the number of pages in the pagination');
    var lenArr = new Array(Math.ceil(this.receiptItems.length / 10));
    var arrayBuffer: ArrayBuffer[] = [];
    var fileURL;
    console.log('creatting main doc');
    for (let index = 0; index < lenArr.length; index++) {
      console.log('Changing pagination to:', index + 1);
      this.page = index + 1;
      await this.sleep(1000);
      console.log('Converting page:', index + 1);
      await new Promise<void>(async (resolve, reject) => {
        ***var doc = new jsPDF('p', 'pt', [496, 702]);***
        doc.html(document.getElementById('receipt'), {
          callback: async (res) => {
            console.log('Adding page to buffer, page:', index + 1);
            arrayBuffer.push(res.output('arraybuffer'));
            if (lenArr.length - 1 == index) {
              console.log('Printing');
              await this.mergePdfs(arrayBuffer);
            }
            resolve();
          },
        });
      });
    }
  }

  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

jsPDF对象似乎保留了 jsPDF.html(...) 的第一个结果,无论此方法是否多次执行。

于 2021-03-25T01:31:26.110 回答