jsPDF和html2canvas丢失空格并导致文本错位

6
我将使用html2canvas和jsPDF在客户端生成pdf。无论我选择什么设置,都会在html到pdf渲染中丢失字母间距作为伪影。
是否有设置可以解决这个问题?我已经查看了API并更改了我能想到的每个可能的设置,但没有任何改变间距的效果。

显示间距丢失的图像

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

enter image description here

之后(pdf):

enter image description here

代码

代码使用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);
      }
    });
  }
2个回答

18

增加非零的letter-spacing CSS似乎可以解决问题。

letter-spacing: 0.01px;

2
感谢您在找到解决方案后与我们分享。您刚刚节省了我大量的时间和研究工作。 - smacdav
你好 @smacdav,我也遇到了渲染的问题,你是在哪里添加 CSS 样式的?是在每个 tspan 上还是父级 svg 上? - undefined
你能编辑并添加一个例子回答吗? - undefined

1
这个问题与你选择的字体族有关。我尝试了不同的字体族,问题就解决了。希望这能帮助到某些人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接