本文介绍了我不能在Angular 10中使用jsPDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用jspdf库打印页面.我已经尝试了许多解决方案,并按照此处的示例以及几乎每个Google建议链接进行了处理,但是我仍然无法解决.

I was trying to print my page using jspdf library. I've tried so many solutions to get it done following examples on here and almost every Google suggestion links but I still couldn't fix it.

这是我到目前为止尝试过的:

Here is what I've tried so far:

import * as jsPDF from 'jspdf';
.....
openPDF(): void {
    const DATA = this.couponPage.nativeElement;
    const doc = new jsPDF('p', 'pt', 'a4');
    doc.fromHTML(DATA.innerHTML, 15, 15);
    doc.output('dataurlnewwindow');
}

尝试如上所述导入jsPDF,在编译时会产生以下错误

Trying to import jsPDF like the above creates the following error while compiling

42     const doc = new jsPDF('p', 'pt', 'a4');

因此,我尝试按照此 stackoverflow答案

declare var jsPDF: any;

但这会创建一个控制台错误,提示未定义jsPDF.

And yet this creates a console error saying that jsPDF is not defined.

然后我找到了另一个解决方案,发布在这里 Angular 10/9/8 PDF教程–使用JSPDF在Angular中导出PDF

Then I found another solution as posted in here Angular 10/9/8 PDF Tutorial – Export PDF in Angular with JSPDF

按照这种方法,现在出现以下错误

And following this method now I got the following error

我不知道我在这里错过了什么,因为这个库应该可以在所有Angular版本中使用.任何帮助将不胜感激.

I've no Idea what I've missed here as this library supposed to work in all Angular versions. Any help will be appreciated.

在这里,我创建了一个 Stackblitz项目

Here I've created a Stackblitz project

推荐答案

为此问题尝试了许多不同的解决方案后,我发现addHTMLfromHTML在最新版本的jspdf中均已贬值.并将它们替换为html.对于那些寻求与jspdfAngular 10一起使用的更好解决方案的人来说,这看起来是可行的,到目前为止,我发现了更好的结果.

After trying so many different solutions for this issue now I've found that both the addHTML and fromHTML is depreciated in latest versions of jspdf and they are replaced with just html. For those who are seeking for a better solution to work with jspdf and Angular 10 here is what looks working and a better result that I've found so far.

要导入jspdf版本(2.x.x),只需执行以下操作:import { jsPDF } from 'jspdf';.

To import jspdf version (2.x.x), just simply do: import { jsPDF } from 'jspdf';.

您将不需要像以前版本中那样将任何依赖项包含在angular.json脚本中.并且,如果在index.html内添加jspdfhtml2canvas脚本,也请删除它们.通过运行npm install jspdf,它还将安装html2canvas,它也由jspdf动态导入.

You won't need to include any of the dependencies into angular.json scripts like you would do in previous versions. And if you add scripts of jspdf or html2canvas insideindex.html, also remove them. By running npm install jspdf it also install the html2canvas which is also dynamically imported by jspdf.

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { jsPDF } from 'jspdf';

.....

 @ViewChild('couponPage', { static: true }) couponPage: ElementRef;

.......

openPDF(): void {
  const DATA = this.couponPage.nativeElement;
  const doc: jsPDF = new jsPDF("p", "mm", "a4");
  doc.html(DATA, {
     callback: (doc) => {
       doc.output("dataurlnewwindow");
     }
  });
}

这篇关于我不能在Angular 10中使用jsPDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:18