30

我收到一个错误:jsPDF 未定义,我目前正在使用以下代码:

import { Component, OnInit, Inject } from '@angular/core';
import 'jspdf';
declare let jsPDF;
@Component({
  ....
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

  constructor(
    @Inject('Window') private window: Window,
    ) { }

  download() {

        var doc = jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');    
        doc.save('Test.pdf');
    }
} 

我已经安装了 jsPDF 的 npm 但不知道如何导入 jspdf 并使用 angular-cli: 1.0.0-beta.17 运行

4

5 回答 5

81

我已经做到了,经过大量的研发,他们的几个步骤如下: 安装:

npm install jspdf --save

typings install dt~jspdf --global --save

npm install @types/jspdf --save

在 angular-cli.json 中添加以下内容:

"scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ]

html:

<button (click)="download()">download </button>

组件 ts:

import { Component, OnInit, Inject } from '@angular/core';
import * as jsPDF from 'jspdf'
@Component({
  ...
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

  constructor(
    @Inject('Window') private window: Window,
    ) { }

  download() {

        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');

        // Save the PDF
        doc.save('Test.pdf');
    }
}
于 2017-01-06T05:41:52.340 回答
10

老问题,但这是我在我的角度应用程序中启动并运行的替代解决方案。我最终修改了这个 jsPDF 解决方案以在不使用 ionic/cordova CLI 的情况下工作。

npm install jspdf --save
npm install @types/jspdf --save
npm install html2canvas --save
npm install @types/html2canvas --save

将 id 添加到包含要生成 PDF 的内容的任何 div

<div id="html2Pdf">your content here</div>

导入库

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

添加生成PDF的方法

generatePdf() {
    const div = document.getElementById("html2Pdf");
    const options = {background: "white", height: div.clientHeight, width: div.clientWidth};

    html2canvas(div, options).then((canvas) => {
        //Initialize JSPDF
        let doc = new jsPDF("p", "mm", "a4");
        //Converting canvas to Image
        let imgData = canvas.toDataURL("image/PNG");
        //Add image Canvas to PDF
        doc.addImage(imgData, 'PNG', 20, 20);

        let pdfOutput = doc.output();
        // using ArrayBuffer will allow you to put image inside PDF
        let buffer = new ArrayBuffer(pdfOutput.length);
        let array = new Uint8Array(buffer);
        for (let i = 0; i < pdfOutput.length; i++) {
            array[i] = pdfOutput.charCodeAt(i);
        }

        //Name of pdf
        const fileName = "example.pdf";

        // Make file
        doc.save(fileName);

    });
}

我发现这个解决方案对我的 Web 应用程序非常有效,并且非常有用,因为我可以控制何时生成 PDF(在异步接收数据之后)。同样,我不需要全局安装任何库。

于 2018-12-05T17:45:33.313 回答
7

在@gsmalhotra 的帮助下,我根据这个答案创建了一个jsPdf演示

首次安装

npm install jspdf --save

我使用了图像数组,首先将图像转换为 base64 (jsPDF 不允许图像 URL)

getBase64Image(img) {
  var canvas = document.createElement("canvas");
  console.log("image");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/jpeg");
  return dataURL;
}

然后在一个循环中,我调用了返回 base64 图像的上述函数,然后使用doc.addImage().

for(var i=0;i<this.images.length;i++){
   let imageData= this.getBase64Image(document.getElementById('img'+i));
   doc.addImage(imageData, "JPG", 10, (i+1)*10, 180, 150);
   doc.addPage();
}

HTML 代码

<div class="col-md-4" *ngFor="let img of images;let i=index">
    <img id="img{{i}}" class="img-fluid" crossOrigin="Anonymous" [src]="img.url">
</div>

演示
代码

于 2018-01-19T16:52:01.783 回答
2

以下是divAngular 11中下载 a 的方式:

  1. 安装 npm 包:
npm install jspdf --save
  1. 将模板引用添加html为:
<div #myTemp>
   // other code here

  <button (click)="print()"></button>
</div>
  1. 导入xyz.component.ts
import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';

export class XYZComponent { 
   @ViewChild('myTemp') myTempRef: ElementRef;

   print(){
    const DATA = this.myTempRef.nativeElement;
    html2canvas(DATA).then(canvas => {        
      let fileWidth = 200;
      let fileHeight = canvas.height * fileWidth / canvas.width;
      
      const FILEURI = canvas.toDataURL('image/png')
      let PDF = new jsPDF('p', 'mm', 'a4');
      let position = 0;
      PDF.addImage(FILEURI, 'PNG', 5, 5, fileWidth, fileHeight)      
      PDF.save('angular-demo.pdf');
    });   
   }
}
于 2021-04-09T13:19:08.137 回答
0

1.安装包

    npm install jspdf

2.像下面这样导入

    import { jsPDF } from 'jspdf'
   // important! using this ES6 syntax you don't need to import the library via the script
      section in angular.json

3.使用它

 // for somereadon the latest version (currenly 2.3)  words with properties 
   of type string only, even if you have dates or numbers, convert them to string first
 let data = [
   {
    id: "123032510",
    firstname: "Benzara Tahar",
    lastname: "Riad",
   },
   {
    loggedInUserId: "1233205",
    firstname: "Matouk",
    lastname: "Aymen",
   }
   ];
  let header = this.createHeaders(['ID', 'Firstname', 'Lastname']);
  let doc = new jsPDF()
  doc.table(1, 1, data, header, {})
  doc.save()
于 2021-01-18T14:31:59.537 回答