在Angular 2上从div创建并下载pdf [英] Create and download pdf from div on angular 2

查看:68
本文介绍了在Angular 2上从div创建并下载pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jsPDF从现有的div创建和下载PDF.

I'm trying to create and download an PDF from an existing div with jsPDF.

我尝试了很多方法,但我无法实现.

I have tried many ways but I can't achieve it.

我的上一次尝试是使用@ViewChildElementRef,但是没有用.

My last try was with @ViewChild and ElementRef but doesn't work to.

detail-devis.component.ts:

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

柱塞

有人知道使用Angular 2实现这一目标的最简单方法吗?

Someone know the simplest way to achieve this with Angular 2?

推荐答案

我想问题是ViewChild给你一个ElementRef这是一个有角类.您应该获取该对象的nativeElement以获得实际的HtmlElement:

I guess the problem is that ViewChild gives you an ElementRef which is an angular class. You should get the nativeElement of this object 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用作方法名称.显然,角度不喜欢那样.您需要重命名.之后,您将遇到缺少库的问题:

In your plunkr you use the name test for a method name. Apparently angular doesn't like that. You need to rename that. After that you will encounter the problem that you are missing a library:

您需要 https://github.com/niklasvh/html2canvas 将其中之一添加到您的项目中,它应该可以工作.请注意,虽然功能addHtml已弃用

Add one of these to your project, and it should work. Note though that the function addHtml is deprecated

我已经制作了一个有效的 plunkr ,在其中添加了html2canvas.

I've made a working plunkr, where I added html2canvas.

这篇关于在Angular 2上从div创建并下载pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆