Create and download pdf from div on angular 2

I am trying to create and load a PDF from an existing div using jsPDF.

I tried many ways, but I can not achieve this.

My last attempt was with @ViewChildand ElementRef, but does not work.

detail-devis.component.ts:

import {Component, ElementRef, ViewChild} from "angular2/core";
declare let jsPDF; 

@Component({
selector: 'my-app',
template: `<div #test>
    Hello world
  </div>
  <button type="button" (click)="test()">pdf</button>
  <button (click)="download()">download</button>`
})

export class App {

  @ViewChild('test') el: ElementRef;

  constructor() {
  }

  public download() {
    var doc = new jsPDF();
    doc.text(20, 20, 'Hello world!');
    doc.save('Test.pdf');
  }

  public test() {
    let pdf = new jsPDF('l', 'pt', 'a4');
    let options = {
      pagesplit: true
    };
    pdf.addHTML(this.el.nativeElement, 0, 0, options, () => {
      pdf.save("test.pdf");
    });
  }
}

Plunker

Does anyone know the easiest way to achieve this with Angular 2?

+4
source share
1 answer

I think the problem is what ViewChildgives you ElementRefwhich is the angular class. You must get nativeElementthis object in order to get the actual HtmlElement:

@ViewChild('test') el:ElementRef;


createPdf(): void {
   let pdf = new jsPDF('l', 'pt', 'a4');
   let options = {
      pagesplit: true
   };
   pdf.addHTML(this.el.nativeElement, 0, 0, options, () => {
      pdf.save("test.pdf");
   });
}

plunkr test . -, angular . . , :

https://github.com/niklasvh/html2canvas https://github.com/cburgmer/rasterizeHTML.js

, . , addHtml

plunkr, html2canvas.

+10

Source: https://habr.com/ru/post/1668271/


All Articles