html2pdf not generating PDF from preview

  Kiến thức lập trình

I have this function to generate my pdf:

private async generatePdf(): Promise<Blob> {
    try {
      this.modalContent.nativeElement.classList.add('prepare-pdf');
      const element = this.modalContent.nativeElement;

      this.renderer.addClass(element, 'prepare-pdf')
      
      // Adjust scale incrementally
      const scale = 2.5; // Adjust scale as needed
      const options = {
        margin:0.5,
        filename: 'cotizacion.pdf',
        image: { type: 'jpeg', quality: 1 },
        html2canvas: {
          scale: scale,
          useCORS: true,
          // Calculate window width and height based on the element's scroll size
          windowWidth: element.scrollWidth * scale,
          windowHeight: element.scrollHeight * scale,
          letterRendering: true,
        },
        jsPDF: { unit: 'pt', format: 'letter', orientation: 'portrait' },
        //pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
      }; 
  
      const worker = html2pdf().from(this.modalContent.nativeElement).set(options);
      const blob = await worker.output('blob');
      
      this.renderer.removeClass(this.modalContent.nativeElement, 'prepare-pdf');
        return blob;
    } catch (error) {
        this.renderer.removeClass(this.modalContent.nativeElement, 'prepare-pdf');
        console.error('Error generating PDF Blob:', error);
        throw error;
    }
  }`

the first problem comes with the scale. If I ever go below 2.5, the pdf won’t show all the information, it cuts halfway through. Also, when the PDF generates, the contents look too big.
This is my preview:
This is how my preview looks in the website, it’s also how the actual PDF should look like.

But the end result is:
Actual PDF

The table elements are all messed up. I’ve tried changing lots of the options as the html2pdf, html2canvas and jsPDF docs recommend and still can’t get it to look like the preview.

Does anybody know what could be causing this issue?

New contributor

Miguel Alveo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT