How to generate a PDF using Angular 7?

119,950

Solution 1

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');
  }

Solution 2

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');   
      }); 
    }

Solution 3

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.

Solution 4

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>

Solution 5

Previous answers didn't work for me. Then I founded this solution. Tested with angular 9.

jspdf version "^2.3.0"

npm install jspdf --save
npm install @types/jspdf --save-dev
  1. Create table in component.html file. <table class="table" id="content" #content></table>

  2. Catch table in component.ts file. @ViewChild('content') content: ElementRef;

savePdf() {
    const doc = new jsPDF();

    const pdfTable = this.content.nativeElement;

    doc.html(pdfTable.innerHTML, {
      callback(rst) {
        rst.save('one.pdf');
      },
      x: 10,
      y: 10
    });

  }

Try this solution.

Share:
119,950
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • Sai Manoj
    Sai Manoj almost 4 years
    Any way to covert the pdf to base64 without downloading the form
  • nipun-kavishka
    nipun-kavishka almost 4 years
    doc.output('blob") will return base64
  • Superman.Lopez
    Superman.Lopez almost 4 years
    This works for me. Whats omitted here is the reference to the element, which can be done by setting an id on the element and the selecting with var nativeElement = document.getElementById('name-used-as-id');
  • zorlac
    zorlac about 3 years
    is the converted pdf's text selectable or searchable? or it is converted to image?
  • kaushik
    kaushik about 3 years
    @zorlac, it is converted to image
  • Jitin
    Jitin about 3 years
    But this doesn't allow you to create styling or alignment. It feels like such a poor way to make a pdf... specifying x-y locations and what not
  • 06serseri
    06serseri almost 3 years
    Is there a documentation or tutorial for angular-pdf-generator, it looks like both GitHub links under npmjs page are not working.
  • sebas2day
    sebas2day over 2 years
    Use doc.html instead of doc.fromHTML
  • Hasher
    Hasher over 2 years
    This works but, keep in mind that if you don't need high quality exports, you can use image/jpeg instead of PNG. This will reduce a two pages file from around 25mb down to just 1mb.
  • Basil
    Basil over 2 years
    @Hasher, I have edited the code to add it in comments.
  • mwilson
    mwilson over 2 years
    It would be great to explain what this code is doing. For example, what are specialElementHandlers and why are they required. They don't seem to exist in the latest version.