Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a PDF using Angular 7?

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?

like image 981
The Bored Theorist Avatar asked Mar 06 '19 09:03

The Bored Theorist


4 Answers

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');
  }
like image 129
DeC Avatar answered Oct 23 '22 03:10

DeC


You need to display the contents to be printed within a DIV. After displaying the contents, use the following code which was used and worked for my project

Step 1 :

Run following commands to install npm packages

> npm install jspdf
> npm install html2canvas

Step 2:

Import installed packages in app.components.ts. I haven't imported those packages in constructor()

> import * as jspdf from 'jspdf';
> import html2canvas from 'html2canvas';

Step 3:

Give an id for the HTML div that has to be exported as PDF. Add a button that activates the function too.

<div id="MyDIv" style="margin-left: 45px;" class="main-container">
        
</div>
<div class="icon_image " title="Share As PDF" (click)="exportAsPDF('MyDIv');"><img src="assets/img/pdf.png"></div>

Step 4 :

call the code for generating PDF as follows

    exportAsPDF(divId)
    {
        let data = document.getElementById('divId');  
        html2canvas(data).then(canvas => {
        const contentDataURL = canvas.toDataURL('image/png')  // 'image/jpeg' for lower quality output.
        let pdf = new jspdf('l', 'cm', 'a4'); //Generates PDF in landscape mode
        // let pdf = new jspdf('p', 'cm', 'a4'); Generates PDF in portrait mode
        pdf.addImage(contentDataURL, 'PNG', 0, 0, 29.7, 21.0);  
        pdf.save('Filename.pdf');   
      }); 
    }
like image 41
Basil Avatar answered Oct 23 '22 02:10

Basil


It is a common requirement, but you haven't provided much detail on specific requirements of your PDFs. You can look at:

https://www.npmjs.com/package/angular-pdf-generator

or

https://parall.ax/products/jspdf

as client-side options. There are other options too depending on what you are likely to want to do with the PDF once generated. For example, it might make more sense to send the data back to your server (if you have one) to generate a PDF AND store it in a database etc.

Hope that helps.

like image 9
Paul Jowett Avatar answered Oct 23 '22 03:10

Paul Jowett


Data entered by the user can be displayed in the HTML page and can be converted to pdf. Else if you want to bind the object in HTML template use handlebars. Then the HTML template can be converted to PDF in angular 2/4/6/7 using jspdf and html2canvas.The HTML content should be processed as below. This code supports for multiple page pdf creation.

Here data --> htmlcontent

TS :

generatePdf(data) {
     html2canvas(data, { allowTaint: true }).then(canvas => {
      let HTML_Width = canvas.width;
      let HTML_Height = canvas.height;
      let top_left_margin = 15;
      let PDF_Width = HTML_Width + (top_left_margin * 2);
      let PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
      let canvas_image_width = HTML_Width;
      let canvas_image_height = HTML_Height;
      let totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
      canvas.getContext('2d');
      let imgData = canvas.toDataURL("image/jpeg", 1.0);
      let pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
      pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
      for (let i = 1; i <= totalPDFPages; i++) {
        pdf.addPage([PDF_Width, PDF_Height], 'p');
        pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
      }
       pdf.save("HTML-Document.pdf");
    });
  }

HTML:

<div #contentToConvert> Some content here </div>

<button (click)="generatePdf(contentToConvert)">Generate PDF</button>
like image 5
Lincy PJ Avatar answered Oct 23 '22 02:10

Lincy PJ