How to generate a PDF using Angular 7?

The Bored Theorist picture The Bored Theorist · Mar 6, 2019 · Viewed 71.3k times · Source

I have to generate a PDF report from data entered by a user, which would be saved in an object. So far, I have come across stuff which generates an HTML page and then takes a screenshot and converts it into PDF. I am looking to generate a PDF directly from data stored in the object. Any ideas?

Answer

DeC picture DeC · Oct 25, 2019

You can use jspdf.

working Demo

.html

<div id="pdfTable" #pdfTable>
  <h1>{{name}}</h1>

  <table>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
   </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
</div>

<div> <button  (click)="downloadAsPDF()">Export To PDF</button></div>

.ts

  public downloadAsPDF() {
    const doc = new jsPDF();

    const specialElementHandlers = {
      '#editor': function (element, renderer) {
        return true;
      }
    };

    const pdfTable = this.pdfTable.nativeElement;

    doc.fromHTML(pdfTable.innerHTML, 15, 15, {
      width: 190,
      'elementHandlers': specialElementHandlers
    });

    doc.save('tableToPdf.pdf');
  }