简体   繁体   中英

Angular 11 and PdfMake. Error TS2345: Argument of type {...} is not assignable to parameter of type TDocumentDefinitions

I'm trying to define pdf document structure accordingly to offical documentation of pdfMake in Angular 11 application. But receiving an error:

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();

I have installed all the staff:

npm install --save pdfmake
npm i --save-dev @types/pdfmake

and imported them:

import * as pdfMake from "pdfmake/build/pdfmake";
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
(<any>pdfMake).vfs = pdfFonts.pdfMake.vfs;

Code:

getPdf() {
    let docDefinition = {
      pageSize: 'A5',
      pageOrientation: 'landscape',
      content: [
        { 
          text: 'Some data', 
          style: 'header'
        },
        {
          text: 'some data 2', fontSize: 15
        }
      ]
    }
    pdfMake.createPdf(docDefinition).open();
  }

When I removing from the method properties definition pageSize and pageOrientation - error dissappear. What else I'm missing?

I found a solution after viewing some posts here on Stackoverflow. Problem was in using pdfMake library (enum types) in TypeScrpit (described by lukasgeiter in this post ).

So, I've changed import of pdfMake library from

import * as pdfMake from "pdfmake/build/pdfmake"; 

to

const pdfMake = require('pdfmake/build/pdfmake.js');

then installed node types by npm:

npm i @types/node

and finally made some changes in tsconfig.app.json file in your Angular app root directoty (add "node" in square brackets in line):

"types": []

after changes:

"types": ["node"]

That's all. Compiler finally starts understand all of content types in document definitions for making pdf in createPdf method from pdfMake library

You can cast it to the exported type from the types lib.

import { PageSize } from 'pdfmake/interfaces';

and create your style like this

pageSize: 'A5' as PageSize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM