Munish Sharma
Munish Sharma

Reputation: 151

convert angular template.html to pdf in angular2 using jspdf

I am new to angular 2 and need functionality to export my html component in angular 2 to pdf using jspdf. I need to convert dynamically generated HTML which is tabular format in to pdf using jspdf. sample code and plunker link is as following:

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

Upvotes: 4

Views: 4225

Answers (1)

Guillermo
Guillermo

Reputation: 71

You can use the autotable:

import autoTable from 'jspdf-autotable'

And in the method pdfHtml() and changue to:

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

Good Luck!

Upvotes: 1

Related Questions