When trying to generate a PDF format with multiple pages based on an ngFor loop in the HTML, I encountered an issue. After clicking a button that redirects to a route for printing the view into a PDF using a library, a blank space appears before the container I specified for printing.
https://i.sstatic.net/fpj67.png
Below is my Angular code snippet showing how I redirect to the route:
print(){
this.router.navigate(['control/pdf']);
And here 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);
}
}
To address the spacing issue, I have added a setTimeout function to allow time for the view to load properly before generating and downloading the PDF file.