使用jspdf在angular2中将angular模板.html转换为pdf

4

我刚接触 Angular 2,需要使用 jspdf 将我的 Angular 2 HTML 组件导出为 PDF。我需要将动态生成的表格格式的 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

(此链接为示例代码的网址)
1个回答

1
您可以使用Autotable:
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");
        });
    }

祝你好运!


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