canvas2html 到 jsPDF - 处理 Promise 的问题

canvas2html to jsPDF - Problem with handling the Promise

我正在使用 jsPDF 将 html 块转换为 PDF 文件。我浏览了 HTML 并检查是否有文本或图像。我对文本使用 doc.text,对图像使用 doc.addImage。我无法处理来自 canvasOutput = html2canvas(input) 的响应,因为它是 Promise。我的代码如下所示:

  for (const element of htmlData) {
    input = document.getElementById(element);
    var typ = input.innerHTML.substring(23, 27);

    if (typ == '<h3>') {
      doc.setFont(fontName, 'bold');
      writeText(input, h3_fontSize, 5);
    } else if (typ == '<h5>') {
      doc.setFont(fontName, 'bold');
      writeText(input, h5_fontSize, 3);
    } else if (typ == '<img') {
      var canvasOutput = html2canvas(input);
      canvasOutput.then((response) => {
        imgData = response.toDataURL('image/jpeg', 1.0);
        doc.addImage(imgData, 'PNG', left_edge_distance, position_mm, 100, 100);
      });
    }
  }

  doc.save('download.pdf');

函数writeText()包含以下代码:

function writeText(input, fontSize, lineSpace) {
    doc.setFontSize(fontSize);
    var content = input.innerHTML.substring(27, input.innerHTML.length - 11);
    var splitText = doc.splitTextToSize(content, max_text_width);
    splitText.forEach((element) => {
      doc.text(element, left_edge_distance, position_mm);
      position_mm = position_mm + fontSize * pixelTrans + lineSpace;
    });
  }

输出文件不包含图像,但是当我在承诺的响应函数中复制 doc.save() 时,图像进入我的 PDF。

我的问题是:如何从 promise 中得到 html2canvas 的结果?

var allPromises = [];
for (const element of htmlData) {
  var input = document.getElementById(element);
  if (input.toLowerCase().startsWith('<img')) {
    allPromises.push(html2canvas(input));
  } else {
    allPromises.push(Promise.resolve(input));
  }
}

Promise.all(allPromises).then(response => {
  response.forEach(input => {
    if (input instanceof String) {
      doc.setFont(fontName, 'bold');
      var isH3 = input.toLowerCase().startsWith('<h3>');
      writeText(input, isH3 ? h3_fontSize : h5_fontSize, isH3 ? 5 : 3);
    } else {
      imgData = input.toDataURL('image/jpeg', 1.0);
      doc.addImage(imgData, 'PNG', left_edge_distance, position_mm, 100, 100);
    }
  });
  doc.save('download.pdf');
});

我会将第一段代码修改为上面的代码,其余部分保持原样。我将在这里解释它的作用:

  1. 维护一系列承诺。
  2. 循环并检查输入是否为图像标签,并将返回的承诺存储到 html2Canvas() 的数组中
  3. 否则,为了维护秩序,只存储已解决的承诺,将输入返回数组。
  4. 运行 Promise.all() 并遍历承诺数组中的每个响应。
  5. 如果是字符串,则写文字,否则添加图片。
  6. 最后,保存一下。