使用 JSPDF 将 Angular template.html 转换为 Angular2 中的 PDF



我是 angular 2 的新手,需要使用 jspdf 将角度 2 中的 html 组件导出到 pdf 的功能。我需要使用 jspdf 将动态生成的表格格式的 HTML 转换为 pdf。示例代码和 plunker 链接如下:

import {Component, ElementRef, ViewChild} from "angular2/core";
declare let jsPDF; 
@Component({
  selector: 'my-app',
    template: `
     <button (click)="pdfHtml()">Download to PDF</button>
    <table #test>
        <thead >
            <th class="my-class">Name</th>
        </thead>
        <tbody>
            <tr *ngFor="#hero of heroes" >
            <td><svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg></td>
                <td>{{hero.name}}</td>
            </tr>
        </tbody>
    </table>
   
   `,
    styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
export class App {
  @ViewChild('test') el: ElementRef;
isClassVisible: true;
 heroes = [
    {id: 1, name:'Superman'},
    {id: 2, name:'Batman'},
    {id: 5, name:'BatGirl'},
    {id: 3, name:'Robin'},
    {id: 4, name:'Flash'},
     {id: 1, name:'Superman'},
    {id: 2, name:'Batman'},
    {id: 5, name:'BatGirl'},
    {id: 3, name:'Robin'},
    {id: 4, name:'Flash'}
];
    constructor() {
    }
    public download() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.save('Test1.pdf');
    }
    
    public pdfHtml() {
      alert(this.el.nativeElement.innerHTML);
        let pdf = new jsPDF();
        let options = {
            pagesplit: true
        };
        pdf.addHTML(this.el.nativeElement, 0, 0, options, () => {
            pdf.save("test1.pdf");
        });
    }
}

示例代码 Plunker

您可以使用自动表:

import autoTable from 'jspdf-autotable'

在方法pdfHtml((和changue中:

    public pdfHtml() {
      alert(this.el.nativeElement.innerHTML);
        let pdf = new jsPDF();
        let options = {
            pagesplit: true
        };
    //Add this
    autoTable(pdf, {
      tableWidth: 'auto',
     // head: [['id', 'Name']],
     head: [['id', 'Name']],
     // body: [ [1, 'Superman', ],[2, 'Batman', ],[3, 'Batgirl', ] ],
     body: heroes ,
     },);
     
        pdf.addHTML(this.el.nativeElement, 0, 0, options, () => {
            pdf.save("test1.pdf");
        });
    }

祝你好运!

最新更新