【问题标题】:jsPDF/html2canvas losing spaces and misaligning text generallyjsPDF/html2canvas 通常会丢失空格和未对齐文本
【发布时间】:2021-10-25 17:35:34
【问题描述】:

我正在使用 html2canvas 和 jsPDF 生成一个 pdf 客户端。无论我选择什么设置,我都会在 html 到 pdf 渲染中丢失字母空格作为伪影。

有解决这个问题的设置吗?我浏览了 API 并更改了我能想到的所有可能的设置,但没有改变间距。

显示空间损失的图像

之前(作为浏览器中的 html):

之后(pdf):

代码

代码使用 html2canvas 和 jsPDF。

async pdfOrder() {
    const doc = new jsPDF({
      orientation: "p",
      unit: "mm",
      format: "a4",
      precision: 5
    });
    const options = {
      background: "white",
      scale: 3
    };

    for (let i = 0; i < this.numberOfPages; i++) {
      const div = document.getElementById("html2Pdf-" + i.toString());
      // create array of promises
      await this.addPage(doc, div, options, i);
    }

    // Name of pdf
    const fileName = "XXX.pdf";

    // Make file
    await doc.save(fileName);
  }

  private addPage(
    doc: jsPDF,
    div: HTMLElement,
    options: any,
    pageNumber: number
  ): any {
    // return promise of canvas to a page
    return html2canvas(div, options).then(canvas => {
      // Converting canvas to Image
      const imgData = canvas.toDataURL("image/PNG");
      // Add image Canvas to PDF
      const bufferX = 4;
      const bufferY = 4;
      const imgProps = (doc as any).getImageProperties(imgData);
      const pdfWidth = doc.internal.pageSize.getWidth() - 2 * bufferX;
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
      if (pageNumber > 0) {
        doc.addPage();
      }
      doc.addImage(
        imgData,
        "JPEG",
        bufferX,
        bufferY,
        pdfWidth,
        pdfHeight,
        undefined,
        "FAST"
      );
      doc.setPage(pageNumber);
      const pdfOutput = doc.output();
      // using ArrayBuffer will allow you to put image inside PDF
      const buffer = new ArrayBuffer(pdfOutput.length);
      const array = new Uint8Array(buffer);
      for (let i = 0; i < pdfOutput.length; i++) {
        array[i] = pdfOutput.charCodeAt(i);
      }
    });
  }

【问题讨论】:

    标签: angular jspdf html2canvas


    【解决方案1】:

    添加非零 letter-spacing css 似乎可以解决问题。

    letter-spacing: 0.01px;
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 2014-10-17
      • 2011-10-29
      • 1970-01-01
      相关资源
      最近更新 更多