如何解决Angular 11 和 PdfMake错误 TS2345:{...} 类型的参数不可分配给 TDocumentDefinitions 类型的参数
我正在尝试根据 Angular 11 应用程序中 pdfMake 的官方文档定义 pdf 文档结构。但是收到错误:
error TS2345: Argument of type '{ pageSize: string; pageOrientation: string; content: ({ text: string; style: string; fontSize?: undefined; } | { text: string; fontSize: number; style?: undefined; })[]; }' is not assignable to parameter of type 'TDocumentDefinitions'.
Types of property 'pageOrientation' are incompatible.
Type 'string' is not assignable to type '"landscape" | "portrait" | undefined'.
75 pdfMake.createPdf(docDefinition).open();
我已经安装了所有人员:
npm install --save pdfmake
npm i --save-dev @types/pdfmake
并导入它们:
import * as pdfMake from "pdfmake/build/pdfmake";
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
(<any>pdfMake).vfs = pdfFonts.pdfMake.vfs;
代码:
getPdf() {
let docDefinition = {
pageSize: 'A5',pageOrientation: 'landscape',content: [
{
text: 'Some data',style: 'header'
},{
text: 'some data 2',fontSize: 15
}
]
}
pdfMake.createPdf(docDefinition).open();
}
当我从方法属性定义中删除 pageSize 和 pageOrientation 时 - 错误消失。 我还缺少什么?
解决方法
在查看 Stackoverflow 上的一些帖子后,我找到了解决方案。问题是在 TypeScrpit 中使用 pdfMake 库(枚举类型)(由 lukasgeiter 中的 post 描述)。
所以,我已经改变了 pdfMake 库的导入
import * as pdfMake from "pdfmake/build/pdfmake";
到
const pdfMake = require('pdfmake/build/pdfmake.js');
然后通过 npm 安装节点类型:
npm i @types/node
最后在您的 Angular 应用根目录中的 tsconfig.app.json 文件中进行了一些更改(在行中的方括号中添加“节点”):
"types": []
更改后:
"types": ["node"]
仅此而已。编译器终于开始理解在 pdfMake 库
中的 createPdf 方法中用于制作 pdf 的文档定义中的所有内容类型版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。