问题描述
生成pdf格式,该格式将根据html中的ngFor生成多个页面,为此,我正在使用一个按钮,该按钮重定向到使用库将视图打印为pdf的路由。 ,在我定义要打印的容器之前会出现一个空白。
在这里,我的代码来自angular,它重定向到路线
print(){
this.router.navigate(['control/pdf']);
}
这是我的pdf组件
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);
}
}
我放置了setTimeout来尝试解决此问题,并在下载pdf之前给它时间来加载视图。
解决方法
如果您认为存在竞争状况,则可以始终使用更改检测来更新模板:
constructor(private cdr: ChangeDetectorRef)....
/// ...after data loaded
this.cdr.detectChanges();
您可能还需要在您的类中定义一个布尔值,并在整个.html文件中放一个<ng-container *ngIf="myBoolean">...pdfStuff...</ng-container>
然后,在获取数据后,可以设置myBoolean = true
;,这将导致仅在该点之后加载页面。
希望这些可以解决问题!
,尝试在html2canvas配置中使用y
和scrollY
选项。
示例:
this.options = {
margin: 0,filename: 'myfile.pdf',image: { type: 'jpg',quality: 0.98 },html2canvas: { scale: 3,y: 0,scrollY: 0},jsPDF: { format: 'A4' },};
如果这不起作用,您也可以尝试在相同的html2canvas选项中添加removeContainer