簡體   English   中英

Angular 11 和 PdfMake。 錯誤 TS2345:類型 {...} 的參數不可分配給 TDocumentDefinitions 類型的參數

[英]Angular 11 and PdfMake. Error TS2345: Argument of type {...} is not assignable to parameter of type 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();
  }

當我從方法屬性定義pageSizepageOrientation 中刪除時- 錯誤消失。 我還缺少什么?

在查看 Stackoverflow 上的一些帖子后,我找到了解決方案。 問題在於在 TypeScrpit 中使用 pdfMake 庫(枚舉類型)(由lukasgeiter在這篇文章中描述)。

所以,我改變了 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

您可以將其轉換為類型庫中的導出類型。

import { PageSize } from 'pdfmake/interfaces';

並像這樣創建你的風格

pageSize: 'A5' as PageSize

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM