Tuesday, 25 August 2020

Html2pdf whitespace using angular

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.



from Html2pdf whitespace using angular

No comments:

Post a Comment