How to generate a PDF using Angular 7?
Asked Answered
M

8

51

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?

Machicolate answered 6/3, 2019 at 9:12 Comment(0)
M
37

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');
  }
Mcreynolds answered 25/10, 2019 at 10:2 Comment(6)
Any way to covert the pdf to base64 without downloading the formFiddlefaddle
doc.output('blob") will return base64Fourteen
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 notMezzorilievo
Use doc.html instead of doc.fromHTMLCatchword
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.Walkway
Now jspdf 2.5.1 version is avilable. The method fromHTML has been changed to html: doc.html(cheque, { callback: (doc) => { doc.save('doc.pdf');}, x: 10, y: 10,}); Also You can all documentation from here: raw.githack.com/MrRio/jsPDF/master/docs/index.htmlPeters
E
25

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');   
      }); 
    }
Earreach answered 13/12, 2019 at 5:8 Comment(6)
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.Lyris
@Hasher, I have edited the code to add it in comments.Earreach
Is there a way to do this with other libs?! I have a component with many sub components, multiple pages of graphs.. can I just put a bit of code in a parent component to turn the page into a single pdf? Instead of defining individual graphs like this?Cyrene
@ScipioAfricanus, We can go with alternative libraries too. You can define a service and the same can be reused in parent comps.Earreach
Hey, I got it working with jsPDF and html2canvas. Just had to tool around with it a bit.Cyrene
@ScipioAfricanus, here also we have made use of the same two libraries only.Earreach
M
9

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.

Manganate answered 8/3, 2019 at 6:53 Comment(1)
Is there a documentation or tutorial for angular-pdf-generator, it looks like both GitHub links under npmjs page are not working.Interatomic
P
8

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>
Pluvial answered 13/12, 2019 at 10:4 Comment(1)
Your answer is just brilliant my friend! It worked perfectly for me!Olshausen
C
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.

Conative answered 16/2, 2021 at 4:50 Comment(0)
P
3

You can print using PDFMAKE plugin. Access it on Git with this link https://www.npmjs.com/package/ng-pdf-make. After the installation is very easy, just import, add these libraries in the component that will print:

import * as pdfMake from "pdfmake/build/pdfmake";

import * as pdfFonts from "pdfmake/build/vfs_fonts";

After that, create a function that will print your document such as:
            
            printDoc(){
            
            pdfMake.vfs = pdfFonts.pdfMake.vfs;
             let dd = {
           
// Here you put the page settings as your footer, for example:
                      footer: function(currentPage, pageCount) {
                          return [
                            {
                              text:
                                currentPage.toString() +
                                " de " +
                                pageCount +
                                "\n" +
                                "Footer Name",
                              alignment: currentPage ? "center" : "center"
                            }
                          ];
                        },
// Here you can enter the page size and orientation:
                pageSize: "A4",
                pageOrientation: "Portrait",
            //in pageOrientation you can put "Portrait" or "landscape"
        
// start the body of your impression:
        content: [
        
                     {
                        table: {
                          widths: ["*"],
                          body: [
                            [
                              {
                                text: [
                                  { text: `${'Text Example'}`, bold: true }
                                ],
                                style: "header",
                                width: "150",
                                alignment: "left",
                                border: [true, true, true, false],
                                margin: [0, 15, 0, 15]
                              }
                            ]
                          ]
                        }
                      },
        ]
        
            }
        
        pdfMake.createPdf(dd).download("Name of Print");
            }
Powered answered 1/10, 2019 at 13:27 Comment(0)
W
1

Install dependencies:

npm install jspdf
npm install html2canvas

my component

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

...
// make gap from left and right sides. In my case container has margin: 0
// that means that after pdf generation, content has no gaps, looks a bit ugly.
pdfView = false;
constructor(private cdRef: ChangeDetectorRef) {}
...

exportAsPdf() {
  // make gap from left and right sides. In my case container has margin: 0
  // that means that after pdf generation, content has no gaps, looks a bit ugly.
  this.pdfView = true;

  // workaround to wait until pdfView will affect page;
  setTimeout(() => {
    let article = document.getElementById('article');

    if (article) {
      const rect = article.getClientRects();
      const h = rect.item(0)!.height;
      const w = rect.item(0)!.width;

      const orientation = h > w ? 'portrait' : 'landscape';

      html2canvas(article).then((canvas) => {
        const contentDataURL = canvas.toDataURL('image/jpeg');
        let pdf = new jspdf.jsPDF(orientation, 'px', [w, h]);
        pdf.addImage(contentDataURL, 'jpeg', 0, 0, w, h);
        pdf.save('Filename.pdf');

        // back margin to 0 after generation.
        this.pdfView = false;
        this.cdRef.detectChanges();
      });
    }
  }, 0);
}

my html

// tailwind class name, mx-2 === margin (left and right) = 0.5rem;
<div id="article" class="mx-2" [ngClass]="{ 'mx-2': servce.pdfView }"> ... </div>

Show case how it works https://youtu.be/Mwe5nGPhhB8

Walling answered 14/2, 2023 at 13:45 Comment(0)
C
-1

The most reliable and easy solution I found with html2pdf.js. I have used it with angular 8. I tried to create stackblitz, but it is having some resolution error. Hence I am pasting the code below:

import * as html2pdf from 'html2pdf.js';

let options = {
        margin: 1,
        filename: 'receipt.pdf',
        html2canvas: { 
          dpi: 192,
          letterRendering: true, 
          allowTaint: true, 
          useCORS: true, 
          logging: false, 
          scrollX: 0,
          scrollY: 0 
        },
        jsPDF: {
          orientation: 'portrait',
          unit: 'cm',
          format: 'a4'
        }
      }; 
      html2pdf().set(options).from(nativeElement).save().finally(() => anyfunc());
Cannibalize answered 8/11, 2019 at 15:0 Comment(4)
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');Swabber
is the converted pdf's text selectable or searchable? or it is converted to image?Corregidor
@zorlac, it is converted to imageCannibalize
@Corregidor image unfortunately.Ithunn

© 2022 - 2024 — McMap. All rights reserved.