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

Generate a compressed file in RAM and then save it to Amazon S3

I'm currently working on a project where I need to compress text data into a zip file in memory using TypeScript and then upload it to an AWS S3 bucket. The input data is in plain text CSV format. However, I seem to be encountering an issue where the ...

When using `type B = A`, B is represented as A. However, if `type B = A | A` is utilized, B appears as 'any'. What causes this change in representation?

import { C } from "https://example.com/type.d.ts"; type D = C | C Playground Upon hovering over D in both the TS Playground and VS Code, it will show as C when declared as type D = C, but display any when declared as type D = C | C. Even if C&a ...

Transform a string into a class in Typescript/Angular

In my application, I've created a reusable modal popup component that takes a string as input and dynamically loads other components based on that input. This approach allows me to use the same modal popup component for multiple modals in the app inst ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Following the build process with the --prod flag in Ionic 3, users may encounter a situation where

Encountering an issue only when using --prod on Android phones. Strangely, touching anywhere triggers the event that should be fired at that specific location, causing the content to suddenly appear. I came across information suggesting a conflict between ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

The dramatist strategically positioning the cursor at the conclusion of an input field

Currently, I am utilizing playwright for my testing purposes and have encountered a specific issue that I am seeking assistance with. The behavior I need to test is as follows: Applying the bold style to existing text within my input field Verifying that ...

Can parameters with identical union types in a function signature be streamlined to contain only the exact same subtypes using generic types?

// defining a type Combinable with string or number as possible values type Combinable = string | number; // function to check if parameter is a string function isString(param: unknown): param is string { return typeof param === "string"; } /** * Func ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure: package.json src/ index.ts common/ index.ts sub/ index.ts My goal is to import certain modules from the package like this: import {...} from '<package>&ap ...

What sets a module apart from a script?

As I delve into the depths of TypeScript documentation to grasp the concept of modules, particularly ES6 modules, I stumbled upon some interesting insights. typescript-modules - this documentation talks about typescript modules and highlights an important ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

Error: The @use directive must come before any other rules in Angular

Error message: Issue: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Error Details: HookWebpackError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js) ...

What is preventing typescript from inferring these linked types automatically?

Consider the following code snippet: const foo = (flag: boolean) => { if (flag) { return { success: true, data: { name: "John", age: 40 } } } return { success: false, data: null } ...

What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet? const fn = (name: string) => { return { [name]: "some txt" }; }; const res = fn("books"); // books or any other string The type of res recognized by TS is: const res: { [x: string]: string ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...