Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate PDF file from html using angular2/typescript

I want to take a part of my HTML template and convert it to PDF file to give the user an option to download it. (After they click a button for example).

I found a library called jsPDF, how would I use jsPDF in an Angular2 app (RC4)?

thank you

like image 987
khalil _diouri Avatar asked Aug 17 '16 12:08

khalil _diouri


2 Answers

If you want to use it in production, you definitely don't want to depend on an internet link being referenced in your index.html, like proposed by @khalil_diouri.

So, to properly use it in an Angular2/Typescript environment, first install it from npm

npm install --save jspdf

If you are using SystemJS, map it in your config file

map: {
    "jspdf": "node_modules/jspdf/dist/jspdf.min.js"
}

Install definition package: (if not installed)

npm install typings --global

Install definition files:

typings install dt~jspdf --global --save

And, finally, import it in your component.ts file

import jsPDF from 'jspdf'
...
    let doc = new jsPDF();
    doc.text(20,20,'Hello world');
    doc.save('Test.pdf');
...
like image 120
crtormen Avatar answered Sep 18 '22 15:09

crtormen


as a response

this link is necessary to import jsPDF content

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script> // to use jsPDF for registring pdf file

then in you component.ts

you do that

declare let jsPDF;

@Component({
    template: `
        <button
          (click)="download()">download
        </button>
        `
})

export class DocSection {


    constructor() {
    }

    public download() {

        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');

        // Save the PDF
        doc.save('Test.pdf');
    }

}
like image 42
khalil _diouri Avatar answered Sep 21 '22 15:09

khalil _diouri