Angular2 - Generate pdf from HTML using jspdf

后端 未结 5 1438
梦如初夏
梦如初夏 2020-12-20 13:09

For a project I\'m working on I need to be able to generate a PDF of the page the user is currently on, for which I\'ll use jspdf. Since I have a HTML

5条回答
  •  执笔经年
    2020-12-20 13:36

    In case someone prefer not to use cdn scripts & would like to use a more (angular) way, this worked for me in Angular 6:

    Using this way will give you better support & autocomplete in the editor & will help you avoid depending on cdn scripts (if you wanna avoid them, like me)

    Based on the excellent answer here & since it was hard for me to find that answer, I am re-sharing what was stated in it & helped me use jsPDF in Angular 6 (all credit goes to the original author of this answer)

    You should run these cmds:

    npm install jspdf --save
    
    typings install dt~jspdf --global --save
    
    npm install @types/jspdf --save
    

    Add following in angular-cli.json:

    "scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ]
    

    html:

    
    

    component ts:

    import { Component, OnInit, Inject } from '@angular/core';
    import * as jsPDF from 'jspdf'
    @Component({
      ...
      providers: [
        { provide: 'Window',  useValue: window }
      ]
    })
    export class GenratePdfComponent implements OnInit {
    
      constructor(
        @Inject('Window') private window: Window,
        ) { }
    
      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');
        }
    }
    

提交回复
热议问题