使用jspdf

时间:2017-03-22 10:31:17

标签: angular typescript jspdf html-to-pdf

我是角度2的新手,需要使用jspdf将我的html组件以角度2导出为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");
        });
    }

}

Sample code Plunker

1 个答案:

答案 0 :(得分:0)

您可以使用自动表:

import autoTable from 'jspdf-autotable'

在pdfHtml()方法中,更改为:

    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");
        });
    }

祝你好运!