2

I need to export my data table to a Pdf file using angular material and I don't know how can I do it exactly then guys plz guide me!

I have tried to use jsPDF and I found that it works on static data and I want to take a copy from my Datatable it should be a way to do that.

my HTML Datatable code source:

 <div class="content-card">
            <mat-table [dataSource]="listdata" matSort class="products-table" [@animateStagger]="{value:'50'}"
                fusePerfectScrollbar>

                <!-- ID Column -->
                <ng-container matColumnDef="icon">
                    <mat-header-cell *matHeaderCellDef mat-sort-header>Icon</mat-header-cell>
                    <mat-cell *matCellDef="let element">
                        <img src="{{element.UrlIconName}}"/>
                    </mat-cell>
                </ng-container>

                <!-- Category Column -->
                <ng-container matColumnDef="Matricule">
                    <mat-header-cell *matHeaderCellDef fxHide mat-sor   t-header fxShow.gt-md>Matricule</mat-header-cell>
                    <mat-cell *matCellDef="let element" fxHide fxShow.gt-md>
                        <p class="category text-truncate">
                            {{element.FullName}}
                        </p>
                    </mat-cell>
                </ng-container>

                <!-- Price Column -->
                <ng-container matColumnDef="Matricule2">
                    <mat-header-cell *matHeaderCellDef mat-sort-header fxHide fxShow.gt-xs>Matricule2</mat-header-cell>
                    <mat-cell *matCellDef="let element" fxHide fxShow.gt-xs>
                        <p class="price text-truncate">
                            {{element.FullName2}}
                        </p>
                    </mat-cell>
                </ng-container>

                <!-- Quantity Column -->
                <ng-container matColumnDef="Departemant">
                    <mat-header-cell *matHeaderCellDef mat-sort-header fxHide fxShow.gt-sm>Departemant</mat-header-cell>
                    <mat-cell *matCellDef="let element" fxHide fxShow.gt-sm>
                        <span>
                            {{element.DepartmentName}}
                        </span>
                    </mat-cell>
                </ng-container>
                <!-- Quantity Column -->
                <ng-container matColumnDef="Etat">
                    <mat-header-cell *matHeaderCellDef mat-sort-header fxHide fxShow.gt-sm>Etat d'inst
                    </mat-header-cell>
                    <mat-cell *matCellDef="let element" fxHide fxShow.gt-sm>

                        <p *ngIf="element.CurrentEquipmentElement; else notShow">
                            <mat-icon class="active-icon green-600 s-16">check</mat-icon>   
                        </p>
                        <ng-template #notShow>
                            <mat-icon class="active-icon red-500 s-16">close</mat-icon>
                        </ng-template>
                    </mat-cell>
                </ng-container>

               <ng-container matColumnDef="Chauffeur">
                    <mat-header-cell *matHeaderCellDef mat-sort-header fxHide fxShow.gt-sm>Chauffeur</mat-header-cell>
                    <mat-cell *matCellDef="let element" fxHide fxShow.gt-sm>
                        <span>
                            {{element.DriverName}}
                        </span>
                    </mat-cell>
                </ng-container>
  ...

                <mat-header-row *matHeaderRowDef="displayedColumns; sticky:true"></mat-header-row>
                <mat-row *matRowDef="let row; columns: displayedColumns;" class="product" matRipple></mat-row>


            </mat-table>
            <mat-toolbar color="white" >
                <mat-toolbar-row >
                    <mat-icon  title="Export as pdf" fxFlex="10">picture_as_pdf</mat-icon>
                    <mat-paginator #paginator [pageSizeOptions]="[5, 10, 25, 100]" [pageSize]="5" fxFlex="90"></mat-paginator>
                </mat-toolbar-row>
            </mat-toolbar>
        </div>
        <!-- / CONTENT CARD -->
    </div>

My component.ts

 this.service.get_cars().subscribe((data)=>{
      //console.log(data);
      this.UIGestionlist = json2array(data);
 this.Listtrackigobjct = this.UIGestionlist[3];
      this.Listtrackigobjct.forEach(e=>{
this.listdata = new MatTableDataSource(this.Listtrackigobjct);
      this.listdata.sort = this.sort;
      this.listdata.paginator = this.paginator;
    });

I've tried using jspdf like:

downloadPdf() {
    this.Listtrackigobjct.forEach(e=>{
      const tempObj = {} as ExportArray;
      tempObj.FullName = e.FullName;
      tempObj.DepartmentName = e.DepartmentName;
      tempObj.DriverName = e.DriverName;
      tempObj.CurrentCarType = e.CurrentCarType;
      tempObj.CurrentCarModelString = e.CurrentCarModelString;
      tempObj.CurrentModelYear = e.CurrentModelYear;
      tempObj.CurrentFuelTypeEnum = e.CurrentFuelTypeEnum;
      tempObj.FuelContainerCapacity = e.FuelContainerCapacity;
      tempObj.MileageFloat = e.MileageFloat;
      prepare.push(tempObj);

    });
    console.log(prepare);
    const doc = new jsPDF();
    doc.autoTable({
        head: [['Matricule','Departemant','Chauffeur','Marque','Modele','Année','Type','Capacite','kilometrage']],
        body: prepare
    });
    doc.save('Vehicules_List' + '.pdf');
  }
}

but the pdf here just show me only the header as the picture here the result

and the body content is something like : [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

for example the first object: FullName: "Mat1" {DepartmentName: "Dep1" DriverName: "Ch1 Ali" CurrentCarType: "Unknown" CurrentCarModelString: "Autre Modèle" CurrentModelYear: 2019 CurrentFuelTypeEnum: "Essence" FuelContainerCapacity: 50 MileageFloat: 713}

6
  • u will not send data as [{}] if u look at my example data i answer array in array and all array is not object array they are string array u convert it to that style Commented Apr 14, 2020 at 11:16
  • Can u share one valid object Commented Apr 14, 2020 at 11:19
  • mmmm I see and how to convert that obj to array? Commented Apr 14, 2020 at 11:22
  • worst way is for loop and put them into array, best way is mapping . If u share one valid object i can write its code Commented Apr 14, 2020 at 11:24
  • [{FullName: "Mat1",DepartmentName: "Dep1",DriverName: "Ch1 Ali",CurrentCarType: "Unknown",CurrentCarModelString: "Autre Modèle",CurrentModelYear: 2019,CurrentFuelTypeEnum: "Essence",FuelContainerCapacity: 50,MileageFloat: 713},{FullName: "123" ,epartmentName: "Dep1",DriverName: "--",CurrentCarType: "Aston_martin",CurrentCarModelString: "Vantage",CurrentModelYear: 1900,CurrentFuelTypeEnum: "Essence",FuelContainerCapacity: 2,MileageFloat: 0}] Commented Apr 14, 2020 at 11:26

2 Answers 2

6

U can use javascript typescript together . jspdf library can solve your problem. Import js pdf 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');
  }
}

Or u can use another way like i edited in stackblitz. use print function to write as pdf https://stackblitz.com/edit/angular-material-table-export-excel-file-jescpr

 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();
Sign up to request clarification or add additional context in comments.

5 Comments

ok, but the body shouldn't be full data? I mean just if U have in ur response Log , Amount and age and U have to display just Log and Amount how to do that?
I didn'T understand what u mean? In head your will put it with your headers, and in body u will fill it with you data which u send it to html to show. head in this code is an example. U can make print function which take parameters that header and data .
Plz check my update. I did Ur proposition and It didn't works
Do u give an input to print function. How can it be a static data ? In body there will be a function input
great - after this answer we dont need to worry how many sub-table we have or not. simply frame new table based on data
5

With TypeScript jsPdf autotable

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

  downloadPdf() {
    const doc = new jsPDF();
    autoTable(doc, { html: '#my_table_id' })
    doc.save('my_table.pdf')
  }

1 Comment

Easy and accurate answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.