krypton
krypton

Reputation: 61

How can we print and download mat-table as pdf

I am unable to download the angular material table as pdf. Using the below code only a blank file is getting downloaded. And can we print the mat-table

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

 print(){
    let doc = new jsPDF(); 
    doc.autoTable({
      head: [['NAme','approved','utilised', 'available','asd','sadadasada','asdas']],
      body: this.dataSource.filteredData //returning [["log1", "$100"], ["log2", "$200"]]
    });
    doc.save('table.pdf')
  }

Upvotes: 0

Views: 3230

Answers (1)

Lovesh Dongre
Lovesh Dongre

Reputation: 1344

I was facing a similar issue like this so I went through jspdf-autotable npm documentation there I realised body requires array of arrays for which I was passing array of objects, just check if you are not making the same mistake.

To convert array of arrays you can use the following

let data = [];
const displayedColumns = ['NAme','approved','utilised', 'available','asd','sadadasada','asdas']

this.dataSource.forEach(obj => {
  let arr = [];
  this.displayedColumns.forEach(col => {
    arr.push(obj[col]);
  });
  data.push(arr);
});

Now we can simply pass this arrays of array to body of jsPDF object

If this problem had a similar issue then the solution will be as follows

print(){
  let doc = new jsPDF(); 
  
let data = [];
const displayedColumns = ['NAme','approved','utilised', 'available','asd','sadadasada','asdas']

this.dataSource.filteredData.forEach(obj => {
  let arr = [];
  this.displayedColumns.forEach(col => {
    arr.push(obj[col]);
  });
  data.push(arr);
});      
  doc.autoTable({
    head: [['NAme','approved','utilised', 'available','asd','sadadasada','asdas']],
    body: data
  });
  doc.save('table.pdf')
}

Upvotes: 1

Related Questions