对于 ES6 模块用户,步骤也非常相似。
如果您像我一样在这里寻找关于 Ionic 4 angular typescript 的解决方案,下面是对我有用的解决方案!
首先你需要通过 npm 安装包,如下所示。
npm install jspdf@latest --save
在我之前的回复中提到之后,有一个由 jsPDF Contributors 制作的字体转换器,您可以在 here 上找到它。使用它上传您的字体文件并将其包含在您的项目中,以便在您的 TS 文件中易于引用的位置,以便它可以与 ts 文件位于同一文件夹中。
-fontname-style.js // <<--- Here (This is the file you downloaded from converter)
-custom.page.module.ts
-custom.page.html
-custom.page.scss
-custom.page.spec.ts
-custom.page.ts
现在在您的 custom.page.ts 中导入以下内容;
import * as jsPDF from 'jspdf';
import './fontname-style.js';
//OPTIONAL (Only import if you want to use autotable)
import 'jspdf-autotable';
import { autoTable as AutoTable } from 'jspdf-autotable';
完成此操作后,只需检查从转换器下载的文件,您应该会在最底部看到以下代码第二个参数上的字体名称。
this.addFont('fontFile.ttf', 'fontName' , '.......');
现在您可以在 custom.page.ts 中创建这样的函数;
//custom.component.ts or custom.page.ts etc.
exportPDF(){
var doc = new jsPDF("p","pt","a4"); // You can set your own paramaters
doc.setFont('fontName');
doc.text('This is a test', 20,20); // You can set your own margins
return doc.save('filename.pdf');
}
现在您应该会看到一个 pdf,其中 20px 左 20px 上边距用您的字体样式说“这是一个测试”:)
可选插件 - 用于 jsPDF 的 AutoTable
如果你想为 jsPDF 使用 autotable 插件,请从 npm 安装以下包。
npm install jspdf-autotable@latest --save
安装后,将这两个导入添加到您的 custom.page.ts。
import 'jspdf-autotable';
import { autoTable as AutoTable } from 'jspdf-autotable';
您可以根据需要创建列和标题数据
在我们添加这些行之前创建的 exportPDF() 函数内部;
//custom.component.ts or custom.page.ts etc.
exportPDF(){
var doc = new jsPDF("p","pt","a4");
doc.setFont('fontName');
doc.text('This is a test', 20,20); // <-- Remove this line
((doc as any).autoTable as AutoTable)({
head: [['Name', 'Email', 'Country']], // <-- Table headers
body: [ // <-- Table body
['David', 'david@example.com', 'Sweden'],
['Castille', 'castille@example.com', 'Norway'],
// ...
],
styles: { font: "fontName" } /* <-- This is for the font to work in your
table */
});
return doc.save('filename.pdf');
}
现在您应该使用您的字体获得一个包含表格的 pdf :)
我希望这对某人有所帮助。