Guide to exporting a data table to a PDF file with Angular Material

I am looking for a way to export my data table to a PDF file using Angular Material. I have tried using jsPDF but it seems to only work with static data. Is there a way to export my dynamic DataTable content to a PDF file?

Below is the HTML source code for my DataTable:

 (insert your HTML DataTable code here)

In my component.ts file, I am fetching data and populating my DataTable like this:

 (insert your component.ts code snippet here)

I have attempted to use jsPDF to download the DataTable as a PDF:

 (insert your downloadPdf() function code here)

However, when I try to generate the PDF, it only includes the header and the body content is displayed as an array. The PDF does not display the actual data from the DataTable. How can I ensure that the PDF includes all the data elements correctly?

For example, the content of the PDF should look like this:

(Insert an example of how the PDF content should look like here)

Answer №1

If you want to use JavaScript and TypeScript together, you can utilize the jspdf library to solve your issue. Simply import jsPDF to your project.

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


downloadPdf() {
    var prepare=[];
    this.Listtrackigobjct.forEach(e=>{
      var tempObj =[];
      tempObj.push(e.FullName);
      tempObj.push(e.DepartmentName);
      tempObj.push( e.CurrentCarType);
      tempObj.push( e.CurrentCarModelString);
      tempObj.push( e.CurrentModelYear);
      tempObj.push(e.CurrentFuelTypeEnum);
      tempObj.push(e.FuelContainerCapacity);
      tempObj.push(e.MileageFloat);
      prepare.push(tempObj);
    });
    const doc = new jsPDF();
    doc.autoTable({
        head: [['Matricule','','Departemant','','Chauffeur','','Marque','','Modele','','Année','','Type','','Capacite','','kilometrage']],
        body: prepare
    });
    doc.save('Vehicules_List' + '.pdf');
  }
}

Alternatively, you can explore another approach as demonstrated in this stackblitz example. Use the print function to generate a PDF:

let printContents, popupWin;
    printContents = document.getElementById(tableId).innerHTML;
    console.log(printContents)
    popupWin = window.open('', '_blank', 'top=0,left=0,height=auto,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
  <html>
    <head>
      <title>Print tab</title>

    </head>
<body onload="window.print();window.close()"><table class="table table-bordered">${printContents}</table></body>
  </html>`
    );
    popupWin.document.close();

Answer №2

Utilizing TypeScript and the convenient library jsPDF autotable

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

  generatePDF() {
    const doc = new jsPDF();
    autoTable(doc, { html: '#my_table_id' })
    doc.save('my_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

Return either a wrapped or base type based on the condition

I am a beginner in TypeScript and I'm struggling to find the right combination of search terms to solve my issue. It seems like using a type condition could be helpful, but I still need to grasp how they function. My goal is to pass a function that p ...

Using TypeScript's `async await` within a nested function invocation

I am having trouble extracting the 'assigned suspect' from the callbacks, as it is showing up as undefined. Strangely, it works fine within an if statement. I believe the issue is related to the await/async functionality. Any assistance would be ...

"Looking to swap out the Angular theme's CSS stylesheet for your entire application? Here's

I was initially facing an issue while trying to import CSS through index.html as I kept getting a MIME type error: enter image description here The browser refused to apply the stylesheet from 'http://localhost:4200/css/pink-bluegrey.css' because ...

Tips for resolving the issue where a radio group in Angular does not impact other items

Here's the code list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklis> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" style="pad ...

Creating a unique custom pipe in Angular 5

Recently, I started learning Angular and encountered an issue that I'm struggling with. I am trying to develop a custom pipe that can convert decimal codes into base64 images and then display them in views. Even though I have the complete code to add ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Failed to install @ngrx/store due to unforeseen issues

Having issues with the installation of @ngrx/store My current setup includes: Node 8.9.3, NPM 5.5.1, Angular CLI 1.7.4, Angular 5.2.0 I am using Angular CLI to create a new Angular application and attempting to add @ngrx/store by running the following c ...

Customizing Angular tooltips based on specific conditions

Is it possible to implement a conditional tool tip? For instance, I am looking to only display the tool tip if cellData[id].length is greater than 120 within a div element. #solution <div matTooltip="Info about the action" class="{{cssCe ...

Displaying a dynamic array in Angular that shows all results, not just the data under a

Trying to grasp the complexities of Angular 5, I am faced with a challenge. The code successfully passes the "id" number from the array to the URL, but when accessing model/1, all objects from the array are displayed instead of just the object under id 1. ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Encountering an issue with TypeScript and Jest when trying to import a file leads to an

Having trouble with using Jest in a TypeScript environment. //myprovider.tsx class MyProvider{ constructor(){} giveMeFive(): int{ return 5; } } export { MyProvider } // myprovider.test.js import { MyProvider } from './myprovider'; ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Is there a way to prevent the user from proceeding to the next step if they haven't finished the initial one?

After successfully creating a multi-step form using shadcn, react-hook form, and zod, I encountered an issue. Even if I haven't completed the input fields, I can still proceed to the next step by clicking the next button. Appointment.ts export const ...

What steps should I take to resolve an unhandled promise error in a React TypeScript application while making an axios POST request?

I am currently working on a .tsx file to implement adding an enterprise feature. Although I can input data, clicking the submit button does not trigger any action. My application includes a page that has a button for adding a new enterprise. Upon clickin ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

"Dealing with Angular 9's mat-table and the pesky ExpressionChangedAfterItHasBeenChecked

I am facing an issue with my Angular 9 component that has multiple mat-tables. One of the tables contains rows with input fields bound to a reactive form array. While binding the table to the form array works well, I encounter an error when loading the for ...

Ways to extract a single value from a FormGroup

Is it possible to extract individual values from a form using JavaScript? JSON.stringify(this.formName.value) If so, what would be the best approach for achieving this? ...

Utilizing Angular to bind properties conditionally

Can a property be conditionally bound in an Angular template? For instance, if I have an Observable with some data <my-component *ngIf="input$ | async as input" [input1]="input.input1" [overrideValue]="input.ove ...

Encountering a hiccup with dependencies during the transition to Angular 9 with jodit-angular

Encountering the following error when attempting to execute the command npm install after migrating Angular to version 9. Error npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...