Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable

I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the solutions I have tried so far either have printing glitches or do not support autoTable functionality like pdfmake-wrapper and ngx-export-as. The last solution I attempted involved using Renderer2 for DOM manipulation, but it does not meet my requirement of seamless CSS class changes without any flickering. Hence, I am reverting back to JSPDF.

To address this issue, I have installed jspdf and jspdf-autotable packages via npm.

"dependencies": {
    ...
    "jspdf": "^1.5.3",
    "jspdf-autotable": "^3.2.4",
    ...
}

In the angular-cli.json file, I have included the necessary scripts:

"scripts": [ 
        "../node_modules/jspdf/dist/jspdf.min.js",
        "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
      ],

In my component.ts file, I have imported these files as follows:

 import * as jsPDF from 'jspdf'; 
 import * as autoTable from 'jspdf-autotable';

I have also experimented with different ways to import jspdf-autotable.

import * as jsPDF from 'jspdf'; 
import 'jspdf-autotable';

Furthermore, I have tried another combination.

import jsPDF = require('jspdf');
import { autoTable as AutoTable } from 'jspdf-autotable';

However, none of these approaches seem to be effective.

// In My component.ts file I'm using sample code as follows:

let columns = ["ID", "Name", "Age", "City"];
var data = [
    [1, "Jonatan", 25, "Gothenburg"],
    [2, "Simon", 23, "Gothenburg"],
    [3, "Hanna", 21, "Stockholm"]
];
const doc = new jsPDF(); // or let doc = new jsPDF.default();
doc.autoTable(columns, data);
doc.save("filename");

During debugging, I encounter the following errors when running the node command to start the app:

a - Property 'autoTable' does not exist on type 'jsPDF'.

b - Error TS2339: Property 'default' does not exist on type 'typeof jsPDF'.

Any helpful insights or suggestions?

Answer №1

If you're wondering how to utilize this, the key is to pass the instance of jsPdf() into the autoTable() function. I had the same query myself until I consulted with developers who clarified that this approach is necessary for proper implementation. The rest of the process can be followed as per the jsdpf documentation.

import { Component, OnInit } from '@angular/core';
import * as jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

const doc = new jsPDF();

const columns = [['First Column', 'Second Column', 'Third Column']];
const data = [
['Data 1', 'Data 2', 'Data 3'],
['Data 1', 'Data 2', 'Data 3']
];

 autoTable(doc, {
      head: columns,
      body: data,
      didDrawPage: (dataArg) => { 
       doc.text('PAGE', dataArg.settings.margin.left, 10);
      }
 }); 

doc.save('table.pdf');

For reference:
Source Code
https://codesandbox.io/s/currying-pine-wjp1g?file=/src/app/app.component.ts
Check out the Live Demo here:

Answer №2

After some research, I managed to find a solution by switching to a different package called PDFMaker.

For more information, be sure to review the documentation and the list of supported browsers.

You can also explore the helpful playground or take a look at an example in Angular 8.

Answer №3

To achieve this, you could consider implementing the following approach:

const pdfLibrary = require('pdf-library');

or

import pdfLibrary from 'pdf-library';

This method assumes that your node_modules directory has been properly set up as part of your path. If you are utilizing the CLI, everything should be in order for you.

Answer №4

Here is a sample code snippet for generating data and creating headers:

var generateData = function (amount) {
    var result = [];
    var data =
    {
        coin: "100",
        game_group: "GameGroup",
        game_name: "XPTO2",
        game_version: "25",
        machine: "20485861",
        vlt: "0"
    };
    for (var i = 0; i < amount; i += 1) {
        data.id = (i + 1).toString();
        result.push(Object.assign({}, data));
    }
    return result;
};

function createHeaders(keys) {
    var result = [];
    for (var i = 0; i < keys.length; i += 1) {
        result.push({
            'id' : keys[i],
            'name': keys[i],
            'prompt': keys[i],
            'width': 65,
            'align': 'center',
            'padding': 0
        });
    }
    return result;
}

Output: https://i.sstatic.net/TTaBY.png

Answer №5

The accurate response for the question is as follows. Sharing in case it may be helpful to someone in the future,

For more information, visit https://github.com/simonbengtsson/jsPDF-AutoTable for autable

To proceed, you should:

npm install jspdf jspdf-autotable

and utilize ES6 syntax,

import jsPDF from 'jspdf'
import 'jspdf-autotable'

const doc = new jsPDF()
doc.autoTable({ html: '#my-table' })
doc.save('table.pdf')

Answer №6

The issue you're encountering is not related to the import statement. The error is actually caused by using doc.autoTable incorrectly. I had a similar problem, but after referring to the official documentation, I found a solution that worked for me.

import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';  

autoTable(doc, { html: '#report-per-depot',startY: 30, });

For more examples and guidance, check out this link: https://github.com/simonbengtsson/jsPDF-AutoTable/blob/master/examples/examples.js

If you need further assistance, refer to the following reference link: https://github.com/simonbengtsson/jsPDF-AutoTable#installation

There's also an excerpt from the provided link:

You have the option to use the exported autoTable method, which is recommended for typescript and different versions of jsPDF.

 import jsPDF from 'jspdf'
 // import jsPDF = require('jspdf') // // typescript without esModuleInterop flag
 // import jsPDF from 'yworks-pdf' // using yworks fork
 // import jsPDF from 'jspdf/dist/jspdf.node.debug' // for nodejs
 import autoTable from 'jspdf-autotable'

 const doc = new jsPDF()
 autoTable(doc, { html: '#my-table' })
 doc.save('table.pdf')

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

Exploring Tailwind's flexibility with custom color schemes

I'm attempting to generate unique hex colors for my React/TypeScript application with Tailwind. Why isn't the background color updating based on the color variable value? Check out my code snippet below: import React, { useState } from &apo ...

When converting a PDF to a PNG, the precious data often disappears in the process

I am currently facing a problem with the conversion of PDF to PNG images for my application. I am utilizing the pdfjs-dist library and NodeCanvasFactory functionality, but encountering data loss post-conversion. class NodeCanvasFactory { create(w, h) { ...

Best practices for receiving messages from SQS in Node.js

I am exploring how to implement SQS in a similar manner as RabbitMQ or Kafka, where we usually set up a listener. However, after going through their documentation, I couldn't find any instructions on how to set up a listener for SQS: Currently, I am ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

Learning to display an error message by clicking the send button in an Angular 2 application

Despite my best efforts, I have struggled to find a solution. I have searched various websites, but everywhere they only show validations on touch or hide the button until the form is valid. How can I implement validations by simply clicking a button? Here ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

Using string interpolation within the onclick event (Ionic 2 + Angular 2)

One question that's troubling me - I'm attempting to pass a string within an "onclick" event in my Ionic 2 app, but it keeps throwing an error. <button onclick="window.plugins.socialsharing.shareViaWhatsApp(null, null, '{{sound.file}}&a ...

The best approach to typing a FunctionComponent in React with typescript

I'm diving into the world of React and TypeScript for the first time. Could someone verify if this is the correct way to type a FunctionComponent? type ModalProps = { children: ReactElement<any>; show: boolean; modalClosed(): void; }; co ...

Display corresponding JSON images of items within an *ngFor loop in Angular

For my latest project, I am using Angular for the front-end and Laravel for the back-end. The issue I'm facing is with displaying images in Angular that are stored in Laravel storage. The image URLs are stored in the database in JSON format like this: ...

Emphasize cells and headers when a cell's value deviates from its initial value

I implemented cell editing in my primeng table. Here is the code: <div class="card"> <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }"> <n ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

One convenient file for displaying toast notifications, alerts, and loaders specifically designed for the most recent version of Angular

I have been working on a design pattern that involves creating code for various informative widgets such as toast, alert, popup, and loader. My question is where in the angular directory structure should this pattern be placed, and is this approach correc ...

Issue with sorting functionality in swimlane/ngx-datatable not functioning properly

Currently working with ngx-datatable version 11.2.0 and facing an issue related to client-side sorting on a column where the value is determined by an evaluated expression. The column contains numerical values representing latitude and longitude, but we ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

I am not sure where the file is stored between selecting it for upload and actually uploading it

Currently, I am developing a web application using C#, Angular, and SQL. I am in the process of creating a feature that allows users to upload an Excel file into the database by clicking a button on the frontend. Upon clicking the button, a dialog box open ...

Exploring Nuxt's Getters with vuex-class for seamless data retrieval

Currently, I am in the process of developing an application using Nuxt and experimenting with vuex for the first time. Despite following numerous tutorials to set it up, I'm encountering difficulties accessing the store and suspect that the issues may ...

Getting a TypeError following the execution of 'npm update' and 'ng build -prod' commands

Recently, I updated my npm modules and attempted to run ng build -prod, a command that had previously been running smoothly. However, I encountered the following error: TypeError: extractedChunk.getNumberOfModules is not a function at ExtractTextPlugi ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...