如何使用Angular将HTML转换为PDF

7

我正在使用Angular,并且想要将一个HTML表格转换成PDF,这是我的component.ts代码:

downloadPDF() {
    const doc = new jsPDF();
    const specialElememtHandlers = {
        '#editor'(element, renderer) {
            return true;
        }
    };

    doc.fromHTML(this.content.nativeElement.innerHTML, 15, 15, {
        width: 190,
        elementHandlers: specialElememtHandlers
    });
    doc.save('test.pdf');
}

我的html代码如下:

<button (click)="downloadPDF()">Save as PDF</button>

我实际上可以下载PDF,但是它完全是白色的。


你能更新你的表格吗?它是动态的还是静态的? - Abhishek Ekaanth
4个回答

17

首先安装这个包

npm install jspdf

然后安装html2canvas包。

npm install html2canvas

使用import语句将其导入组件中。

import * as jspdf from 'jspdf';  
import html2canvas from 'html2canvas'; 

在您的TS代码中:

import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';  
import * as jspdf from 'jspdf';  
import html2canvas from 'html2canvas';  

@Component({  
  selector: 'app-htmltopdf',  
  templateUrl: './htmltopdf.component.html',  
  styleUrls: ['./htmltopdf.component.css']  
})  
export class HtmltopdfComponent{  
  public captureScreen()  
  {  
    var data = document.getElementById('contentToConvert');  //Id of the table
    html2canvas(data).then(canvas => {  
      // Few necessary setting options  
      let imgWidth = 208;   
      let pageHeight = 295;    
      let imgHeight = canvas.height * imgWidth / canvas.width;  
      let heightLeft = imgHeight;  

      const contentDataURL = canvas.toDataURL('image/png')  
      let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
      let position = 0;  
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)  
      pdf.save('MYPdf.pdf'); // Generated PDF   
    });  
  }  
}

1
如果这是一个具有可变大小的 div,该怎么办? - Ulises CT
@UlisesCT,您是否仍然遇到此问题? - Abhishek Ekaanth

2

1
首先安装此软件包。
npm install jspdf
npm install html2canvas@1.0.0-alpha.12 //working with this html2canvas version.

使用import语句(app.component.ts)将其导入到我们的组件中。

import * as jspdf from 'jspdf';  
import html2canvas from 'html2canvas'; 

添加 app.component.html 文件。
<div class="abc" id="content">
    <h1>Hello World!</h1>
    <button (click)="Screen()">make pdf</button>
</div>

添加 app.component.ts 文件。
Screen()
{  
    var data = document.getElementById('content');  
    html2canvas(data).then(canvas => {  
        // Few necessary setting options  
        var imgWidth = 208;   
        var pageHeight = 295;    
        var imgHeight = canvas.height * imgWidth / canvas.width;  
        var heightLeft = imgHeight;  

        const contentDataURL = canvas.toDataURL('image/png')  
        let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
        var position = 0;  
        pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)  
        pdf.save('MYPdf.pdf'); // Generated PDF   
    });  
}

谢谢。您知道如何发送文档而不是下载吗? - Sathiamoorthy

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接