Search code examples
javascripthtmlangulartypescript

Printing a HTML template as PDF - Angular 2


I am trying to use jsPDF to print my HTML template as a PDF, but I get an error. How should I do it?

Let's say that I have this template:

<div style="text-align:center;" class="sub-header col-lg-12 col-md-12 col-sm-12">
    <span class="welcome-message col-lg-12 col-md-12 col-sm-12">Hola mundo</span>
</div>

Solution

  • At the end, what I have used is this two links:

    1st link It is used to check how to install the needed library: Link

    npm install jspdf --save

    npm install @types/jspdf --save

    angular-cli.json

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

    2nd link Used as a model to developed the needed code (sorry but this answer is in Spanish)

    Link

    Component TS

      pruebaDivAPdf() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        var source = $('#imprimir')[0];
    
        var specialElementHandlers = {
          '#bypassme': function (element, renderer) {
            return true
          }
        };
        var margins = {
          top: 60,
          bottom: 40,
          left: 20,
          width: 522
        };
    
        pdf.fromHTML(
          source,
          margins.left, // x coord
          margins.top, { // y coord
            'width': margins.width,
            'elementHandlers': specialElementHandlers
          },
    
          function (dispose) {
            pdf.save('Prueba.pdf');
          }, margins
        );
      }
    

    Component HTML

    <a (click)="pruebaDivAPdf()" class="button">Pasar a PDF</a>