Html2pdf whitespace using angular

Viewed 1893

to generate a pdf format that will generate several pages according to an ngFor in the html, for this I am using a button that redirect to a route that prints the view into a pdf using the library, the problem is that when printed, a blank space appears before the container that I defined to be printed.

enter image description here

Here I have my code from angular which redirects to the route

print(){
this.router.navigate(['control/pdf']);

}

And this is my pdf component

export class PdfComponent implements OnInit, AfterViewInit {
  options;
  element;
  html: html2pdf;
  constructor(private router: Router) {
  }

  ngOnInit(): void {
     this.options = {
          margin: 0,
          filename: 'myfile.pdf',
          image: { type: 'jpg', quality: 0.98 },
          html2canvas: { scale: 3 },
          jsPDF: { format: 'A4' },
        };
        this.element = document.getElementById('element-to-print');
        this.html = html2pdf().set(this.options).from(this.element);
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      Swal.fire({
        title: 'Wait',
        html: 'The file is being generated',
        timer: 2000,
        onBeforeOpen: () => {
          Swal.showLoading()
        }
      }).then(
        ()=>{
          this.html.save();
          Swal.fire({
            title: "Success!",
            html: "The file has been downloaded successfully",
            icon: 'success',
          });
          this.router.navigate(['control'])});
    }, 4000);
  }
}

I put a setTimeout to try to fix this problem and give it time to load the view before downloading the pdf.

2 Answers

Try using y and scrollY option in html2canvas configuration.

Example :

 this.options = {
      margin: 0,
      filename: 'myfile.pdf',
      image: { type: 'jpg', quality: 0.98 },
      html2canvas: { scale: 3, y: 0,  scrollY: 0},
      jsPDF: { format: 'A4' },
    };

If that doesn't work, you can also try adding removeContainer in the same html2canvas options

If you think there is a race condition you could always use change detection to update the template:

constructor(private cdr: ChangeDetectorRef)....

 /// ...after data loaded
this.cdr.detectChanges();

You may also need to define a boolean in your class, and surrounding the entire .html file put a <ng-container *ngIf="myBoolean">...pdfStuff...</ng-container>

Then, after you get data, you can set myBoolean = true;, which would result in the page loading only after that point.

Hope these solve the issue!

Related