Search code examples
angularjspdfhtml2canvas

jsPDF/html2canvas losing spaces and misaligning text generally


I'm generating a pdf client-side using using html2canvas and jsPDF. No matter what settings I choose I'm getting letter spaces lost as artifacts in the html to pdf rendering.

Is there a setting to fix this? I've gone through the APIs and changed every possible setting I can think of by nothing changes the spacing.

Images showing space loss

Before (as html in browser):

enter image description here

After (pdf):

enter image description here

Code

Code is using html2canvas and 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);
      }
    });
  }

Solution

  • Adding non-zero letter-spacing css seems to fix.

    letter-spacing: 0.01px;