Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to export html to pdf?

How do I make a download button for saving HTML div content as PDF file inside my angular2 project?

This is the HTML content

<div id="obrz">
  <br><br>
  <p class="float-right font-weight-bold">Образац ЗПО</p>
  <br>
  <p class="float-left font-weight-bold">Подаци о обвезнику:</p>

  <br>

  <div class="row" style="width:100%">
    <div class="col-md-2"><p>Порески обвезник:</p></div>
    <div class="col-md-10"><input value="{{userModel.imeIprezime}}" type="text" class="form-control form-control-sm border-1 border-top-0 border-right-0 border-left-0" style="border-bottom: 1px solid black"></div>
    <div class="col-md-2"><p>ПИБ:</p></div>
    <div class="col-md-10"><input value="{{userModel.PIB}}" type="text" class="form-control form-control-sm border-1 border-top-0 border-right-0 border-left-0" style="border-bottom: 1px solid black"></div>
    <div class="col-md-2"><p>Адреса:</p></div>
    <div class="col-md-10"><input value="{{userModel.ulica + ' ' + userModel.broj + ' ' + userModel.grad}}" type="text" class="form-control form-control-sm border-1 border-top-0 border-right-0 border-left-0" style="border-bottom: 1px solid black"></div>
    <div class="col-md-2"><p>Општина:</p></div>
    <div class="col-md-10"><input value="{{userModel.opstina}}" type="text" class="form-control form-control-sm border-1 border-top-0 border-right-0 border-left-0" style="border-bottom: 1px solid black"></div>
  </div>
  <br>
  </div>

P.S. I tried this jsPDF example, but it simply doesn't work for me

Thanks in advance

like image 728
JozeV Avatar asked Jul 17 '18 15:07

JozeV


2 Answers

Try something like this:

Create a button outside of your div

<button (click)="downloadPdf()">Download PDF</button>

When clicked, it will call this function in your component:

downloadPdf() {
    let doc = new jsPDF();
    doc.addHTML(document.getElementById("obrz"), function() {
       doc.save("obrz.pdf");
    });
}
like image 66
birwin Avatar answered Oct 13 '22 02:10

birwin


JSPDF works for angular 2. You need to download the definitions from dt~. Import the library as:

import * as jsPDF from "jspdf";

let doc = new jsPDF();

// Add a title to your PDF
doc.setFontSize(30); 
doc.text(12, 10, "Your Title");

// Create your table here (The dynamic table needs to be converted to canvas).
let element = <HTMLScriptElement>document.getElementsByClassName("pvtTable") 
 [0];
html2canvas(element)
.then((canvas: any) => {
doc.addImage(canvas.toDataURL("image/jpeg"), "JPEG", 0, 50, 
doc.internal.pageSize.width, element.offsetHeight / 5 );
doc.save(`Report-${Date.now()}.pdf`);
})

In your system.js, in the map section add this line:

"jspdf": "<myLibs>/jspdf.js",
like image 25
Bharat Satija Avatar answered Oct 13 '22 03:10

Bharat Satija