Pdf export in EJ2 TypeScript Treegrid control

1 Sep 202524 minutes to read

PDF export allows exporting TreeGrid data to PDF document. You need to use the
pdfExport method for exporting. To enable PDF export in the treegrid, set the allowPdfExport as true.

To use PDF export, inject the PdfExport module in treegrid.

import { TreeGrid, Page, Toolbar, PdfExport } from '@syncfusion/ej2-treegrid';
import { sampleData } from './datasource.ts';

TreeGrid.Inject(Page, Toolbar, PdfExport);

let treeGridObj: TreeGrid = new TreeGrid({
    dataSource: sampleData,
    childMapping: 'subtasks',
    allowPdfExport: true,
    allowPaging: true,
    height: 220,
    pageSettings: {pageSize: 7},
    toolbar: ['PdfExport'],
    treeColumnIndex: 1,
    columns: [
            { field: 'taskID', headerText: 'Task ID', width: 90, textAlign: 'Right' },
            { field: 'taskName', headerText: 'Task Name', width: 180, textAlign: 'Left' },
            {
                field: 'startDate', headerText: 'Start Date', width: 90, textAlign: 'Right', type: 'date', format: 'yMd'
            },
            { field: 'duration', headerText: 'Duration', width: 80, textAlign: 'Right' }
    ]
});

treeGridObj.appendTo('#TreeGrid');
treeGridObj.toolbarClick = (args: Object) => {
if (args['item'].text === 'PDF Export') {
        treeGridObj.pdfExport();
    }

}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-grids/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-treegrid/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-dropdowns/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-calendars/styles/material.css" rel="stylesheet" />
    
    
    
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>   
    </div>
</body>
</html>

Custom data source

PDF export provides an option to define datasource dynamically before exporting. To export data dynamically, define the dataSource in exportProperties

import { TreeGrid, Page, Toolbar, PdfExport, PdfExportProperties } from '@syncfusion/ej2-treegrid';
import { sampleData } from './datasource.ts';

TreeGrid.Inject(Page, Toolbar, PdfExport);

let treeGridObj: TreeGrid = new TreeGrid({
    dataSource: sampleData,
    childMapping: 'subtasks',
    allowPdfExport: true,
    allowPaging: true,
    height: 220,
    pageSettings: {pageSize: 7},
    toolbar: ['PdfExport'],
    treeColumnIndex: 1,
    columns: [
            { field: 'taskID', headerText: 'Task ID', width: 90, textAlign: 'Right' },
            { field: 'taskName', headerText: 'Task Name', width: 180, textAlign: 'Left' },
            {
                field: 'startDate', headerText: 'Start Date', width: 90, textAlign: 'Right', type: 'date', format: 'yMd'
            },
            { field: 'duration', headerText: 'Duration', width: 80, textAlign: 'Right' }
    ]
});

treeGridObj.appendTo('#TreeGrid');
treeGridObj.toolbarClick = (args: Object) => {
if (args['item'].text === 'PDF Export') {
        let exportProperties: PdfExportProperties = {
            dataSource: sampleData,
        };
        treeGridObj.pdfExport(exportProperties);
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-grids/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-treegrid/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-dropdowns/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-calendars/styles/material.css" rel="stylesheet" />
    
    
    
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>   
    </div>
</body>
</html>

Exporting custom aggregates in TreeGrid

The TreeGrid enables exporting custom aggregates, which summarize column data, to an PDF document using the pdfAggregateQueryCellInfo event.

In the provided example, the customAggregateFn function computes the item count for a selected category, while the pdfAggregateQueryCellInfo event customizes the exported cell values in the PDF document.

import { TreeGrid, Page, Aggregate, Toolbar, PdfExport } from '@syncfusion/ej2-treegrid';
import { DropDownList } from '@syncfusion/ej2-dropdowns';
import { summaryData } from './datasource.ts';
import { getObject, CustomSummaryType, AggregateQueryCellInfoEventArgs } from '@syncfusion/ej2-grids';

TreeGrid.Inject(Page, Aggregate, Toolbar, PdfExport);

let selectedCategory: string = 'Seafood';
let categoryDropdown: DropDownList | null = null;
const categoryOptions: { [key: string]: Object; }[] = [
  { food: 'Seafood' },
  { food: 'Dairy' },
  { food: 'Edible' },
  { food: 'Crystal' },
];

//Custom aggregate function to calculate the count of items for the selected category.
const customAggregateFn: CustomSummaryType = (data: object): number => {
  const records: any = (data as any).result ? getObject('result', data) : data;
  return records.reduce((count: number, item: Object) => {
    const category = getObject('category', item) as string;
    return category === selectedCategory ? count + 1 : count;
  }, 0);
};

//Handles the 'pdfAggregateQueryCellInfo' event to customize aggregate cells during PDF export.
const formatPdfAggregateCell = (args: AggregateQueryCellInfoEventArgs): void => {
  if ((args.cell as any).column.headerText === 'Category') {
    args.value = `Count of ${selectedCategory} : ${(args.row as any).data.category.Custom}`;
  }
};

//Initializes a DropDownList in the footer for category selection.
const onDataBound: any = () => {
  if (categoryDropdown && categoryDropdown.element && categoryDropdown.element.classList.contains('e-' + categoryDropdown.getModuleName())) {
    categoryDropdown.destroy();
  }

  categoryDropdown = new DropDownList({
    dataSource: categoryOptions,
    fields: { value: 'food' },
    placeholder: 'Select a Category',
    width: '110px',
    value: selectedCategory,
    change: () => {
      setTimeout(() => {
        if (categoryDropdown && categoryDropdown.value) {
          selectedCategory = categoryDropdown.value.toString();
          treeGrid.refresh();
        }
      }, 300);
    }
  });
  categoryDropdown.appendTo('#customers');
}

const treeGrid = new TreeGrid({
  dataSource: summaryData,
  childMapping: 'subtasks',
  width: 'auto',
  height: 400,
  treeColumnIndex: 1,
  gridLines: 'Both',
  allowPdfExport: true,
  pdfAggregateQueryCellInfo: formatPdfAggregateCell,
  toolbar: ['PdfExport'],
  dataBound: onDataBound,
  columns: [
    { field: 'ID', headerText: 'Order ID', width: 115, textAlign: 'Left' },
    { field: 'Name', headerText: 'Shipment Name', width: 230, clipMode: 'EllipsisWithTooltip' },
    { field: 'shipmentDate', headerText: 'Shipment Date', width: 135, type: 'date', format: 'yMd', textAlign: 'Right' },
    { field: 'category', headerText: 'Category', width: 220, minWidth: 210 },
    { field: 'units', headerText: 'Total Units', width: 90, type: 'number', textAlign: 'Right' },
    { field: 'unitPrice', headerText: 'Unit Price($)', width: 100, type: 'number', format: 'C2', textAlign: 'Right' },
    { field: 'price', headerText: 'Price($)', width: 140, format: 'C0', textAlign: 'Right', type: 'number' },
  ],
  aggregates: [{
    showChildSummary: false,
    columns: [
      {
        type: 'Custom',
        customAggregate: customAggregateFn,
        columnName: 'category',
        format: 'C2',
        footerTemplate: (data: any) => {
          return `<span>Count of <input type="text" id="customers" /> : ${data.Custom}</span>`;
        }
      },
    ]
  }]
});

treeGrid.appendTo('#TreeGrid');

treeGrid.toolbarClick = (args: any) => {
   if (args.item.text === 'PDF Export') {
      treeGrid.pdfExport({
        pageOrientation: 'Landscape'
      });
    } 
};
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-grids/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-treegrid/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-dropdowns/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-calendars/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.1.29/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>        
    </div>
</body>
</html>

You can refer to our JavaScript Tree Grid feature tour page for its groundbreaking feature representations. You can also explore our JavaScript Tree Grid example JavaScript Tree Grid example to knows how to present and manipulate data.