Incorporate the pdfmake.js file into my TypeScript file

Working on a VSTS web extension and looking to utilize PDFmake.js to generate a pdf. The PDFmake.js file needs to be imported into the node_nodules folder by running npm install pdfmake.

To import this JavaScript file into my TypeScript file, I'm following these steps:

import pdfmake = require("../node_modules/pdfmake/build/pdfmake");

However, when attempting this method, it results in the following error:

Severity    Code    Description Project File    Line    Suppression State
Error   TS5055  Cannot write file 'D:/TFS/DM Helper Tools/DEV/WebExtension/RapidCCB/build/pdfmake.js' because it would overwrite input file.    <Unknown>       1   Active

Answer №1

By combining the require and import methods, I was able to find a solution without making any special changes to tsconfig.json. Although I used pdfmake-unicode in my particular case, vfs_fonts should function similarly, I believe.

// on pdfmake: 0.1.38, pdfmake-unicode: 0.0.1

To install:

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

To import:

const pdfMakeX = require('pdfmake/build/pdfmake.js');
const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';

To generate:

downloadTest = () => {
    const docDefinition = {
        content: [{
            table: {
                headerRows: 1,
                widths: ['*', 'auto', 100, '*'],
                body: [
                    ['First', 'Second', 'Third', 'Последняя'],
                    ['Value 1', 'Value 2', 'Value 3', 'Value 4'],
                    [{ text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Чё']
                ]
            }
        }]
    };
    pdfMake.createPdf(docDefinition).download('pdfmake.pdf');
}

To use:

<button onClick={this.downloadTest}>Download</button>

Answer №2

To implement this solution:

Step one,

npm install pdfmake --save

Next, add the following to typings.d.ts:

declare module 'pdfmake/build/pdfmake.js';
declare module 'pdfmake/build/vfs_fonts.js';

Thirdly, in the file where pdfMake is being utilized, whether it's a component or service, include the lines below:

import * as pdfMake from 'pdfmake/build/pdfmake.js';
import * as pdfFonts from 'pdfmake/build/vfs_fonts.js';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES5",
    "forceConsistentCasingInFileNames": true,
    "strictNullChecks": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "typeRoots": [],
    "types": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
  },
  "exclude": ["node_modules"]
}

Lastly, utilize pdfMake.xxx() as needed.

For more information, refer to this link

Answer №3

If you are working with "Typescript", follow these steps:

  • First, you need to install the necessary package:
npm i pdfmake --save
  • Next, import the required modules:
import * as pdfMake from "pdfmake / build / pdfmake";
import * as pdfFonts from 'pdfmake / build / vfs_fonts';

(pdfMake as any).vfs = pdfFonts.pdfMake.vfs;

Answer №4

Check out this Angular 7 component inspired by the example from @Ruslan.

import {Component, Input, OnInit} from '@angular/core';

// set up the pdf settings
import * as pdfMakeConfig from 'pdfmake/build/pdfmake.js';
import * as pdfFontsX from 'pdfmake-unicode/dist/pdfmake-unicode.js';
pdfMakeConfig.vfs = pdfFontsX.pdfMake.vfs;

// import necessary libraries
import * as pdfMake from 'pdfmake/build/pdfmake';

@Component({
  selector: 'app-pdf',
  templateUrl: './pdf.component.html',
  styleUrls: ['./pdf.component.scss']
})
export class PdfComponent implements OnInit {
  // check https://pdfmake.github.io/docs/ for more info
  @Input() pdf: any;
  @Input() filename = 'download.pdf';
  @Input() demo: boolean;

  constructor() { }

  ngOnInit() {
    if (this.demo) {
      this.pdf = {content: [
          {text: 'PdfComponent Example', style: 'header'},
          {text: 'This was generated using Angular and PdfMake', style: 'body'},
          {text: 'PdfMake', link: 'https://pdfmake.github.io/docs/', style: 'link'}
        ],
        styles: {
          header: {
            fontSize: 22,
            bold: true
          },
          body: {
            fontSize: 12
          },
          link: {
            fontSize: 12,
            color: '#03A9F4'
          }
        }
      };
    }
  }

  downloadTest() {
    pdfMake.createPdf(this.pdf).download(this.filename);
  }

}
<button (click)="downloadTest()">Download</button>

Answer №5

If you are trying to integrate this solution with Ionic 5 & Angular 10 using pdfMake v0.1.68, simply follow the instructions below for the necessary imports:

import { Component, OnInit } from '@angular/core';
const pdfMake = require('pdfmake/build/pdfmake.js');
const pdfFonts = require("pdfmake/build/vfs_fonts");
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';

@Component({
....
....
})
export class pdfPage implements OnInit {
...
    

  createPDF(){

     if(this.platform.is('cordova')){

     }else{
      pdfMake.createPdf(docDefinition).download('pdfmake.pdf');
     }
  }
}

If you encounter the following error during build/serve:

error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

To resolve this issue, execute the command:

npm i @types/node

and modify only /tsconfig.app.json as shown below:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"] <---- add this line ONLY
  },

Answer №6

const pdfGenerator = require('pdfmake');
const vfsFonts = require('pdfmake/build/vfs_fonts');

(pdfGenerator).vfs = vfsFonts.pdfMake.vfs;

I've successfully implemented this in my Vue.js project using PDFMake version "^0.2.7".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

What is the best way to define types for an array of objects with interconnected properties?

I need to define a type for an object called root, which holds a nested array of objects called values. Each object in the array has properties named one (of any type) and all (an array of the same type as one). Below is my attempt at creating this type d ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

I am having issues with the Okta Angular sign-in widget as it is not redirecting

Recently, I integrated the Okta angular sign-in widget into my project, but I encountered an issue. In my application, I have multiple modules including an authentication module that manages sign-in, sign-out, and sign-up functionalities. The route I ult ...

Developing a Universal Type in Typescript

Encountered an issue with generic types while working on a user-defined type(interface) structured like this: IList1: { prop1: string, prop2: number, prop3: string . . . } ILi ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

I'm looking for a way to modify the Turkish characters and spaces in the names of JSON data objects. I plan to do this using WebApi

I am facing an issue with fetching data through an API. The JSON data format contains Turkish characters and spaces, causing problems when trying to display the data in a datatable. I have attempted to use the replace and parse functions, but so far, I hav ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

Ways to eliminate duplicate objects from an array using Angular 6

I'm having trouble removing duplicate value objects in an array and it's not working as expected. I believe the duplicate function is functioning correctly, but the changes are not being reflected in the li list. Can you pinpoint where I need to ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

nodemon failing to automatically refresh files in typescript projects

I am currently developing an app using NodeJs, express, typescript, and nodemon. However, I am encountering an issue where the page does not refresh when I make changes to the ts files. Is there a way for me to automatically compile the ts files to js an ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

An issue arises when trying to utilize meta tags in Nuxtjs while incorporating TypeScript into the

When working with Nuxtjs, I encountered an issue regarding my permissionKeys on the page and checking user access in the middleware. Everything runs smoothly when my script language is set to js, but errors arise when set to lang="ts". I tried to find a s ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...