How to export Flutter DataTable to PDF document and save it as file?
The Syncfusion Flutter DataTable widget allows you to export the content to PDF with several customizing options.
The following steps explain how to export the Syncfusion Flutter DataTable’s content to PDF:
STEP 1: Create Employee DataGridSource class by extending the DataGridSource for mapping data to the SfDataGrid.
class EmployeeDataGridSource extends DataGridSource { EmployeeDataGridSource({required List<Employee> employeeData}) { _employeeData = employeeData .map<DataGridRow>((Employee dataGridRow) => DataGridRow(cells: <DataGridCell>[ DataGridCell<int>(columnName: 'ID', value: dataGridRow.id), DataGridCell<String>(columnName: 'Name', value: dataGridRow.name), DataGridCell<String>( columnName: 'Designation', value: dataGridRow.designation), DataGridCell<int>( columnName: 'Salary', value: dataGridRow.salary), ])) .toList(); } List<DataGridRow> _employeeData = <DataGridRow>[]; @override List<DataGridRow> get rows => _employeeData; @override DataGridRowAdapter buildRow(DataGridRow row) { return DataGridRowAdapter( cells: row.getCells().map<Widget>((DataGridCell cell) { return Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: Text(cell.value.toString()), ); }).toList()); } }
STEP 2: To save the file as a PDF document, it is necessary to include mobile, web, and desktop platform-specific file generating code. So, we have provided the common method calledas saveAndLaunchFile to save the exported content as a file. We builthave created two dart files (save_file_mobile_desktop and save_file_web) to save and launch the file in on different platforms.
To access the path from mobile and desktop platforms, you need to add the path_provider package as a dependency in your application. To download the PDF file in the web platform, you should add AnchorElement from dart:html library in save_file_web file.
save_file_web.dart
import 'dart:async'; import 'dart:convert'; import 'dart:html'; ///To save the PDF file in the web platform. Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async { AnchorElement( href: 'data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}') ..setAttribute('download', fileName) ..click(); }
Import io packages in save_file_mobile_desktop file, to save the file. To open the exported file from the given directory, you should import open_file packages.
save_file_mobile_desktop.dart
import 'dart:io'; import 'package:open_file/open_file.dart' as open_file; import 'package:path_provider/path_provider.dart' as path_provider; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart' as path_provider_interface; ///To save the PDF file in the Mobile and Desktop platforms. Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async { String? path; if (Platform.isAndroid || Platform.isIOS || Platform.isLinux || Platform.isWindows) { final Directory directory = await path_provider.getApplicationSupportDirectory(); path = directory.path; } else { path = await path_provider_interface.PathProviderPlatform.instance .getApplicationSupportPath(); } final String fileLocation = Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'; final File file = File(fileLocation); await file.writeAsBytes(bytes, flush: true); if (Platform.isAndroid || Platform.isIOS) { await open_file.OpenFile.open(fileLocation); } else if (Platform.isWindows) { await Process.run('start', <String>[fileLocation], runInShell: true); } else if (Platform.isMacOS) { await Process.run('open', <String>[fileLocation], runInShell: true); } else if (Platform.isLinux) { await Process.run('xdg-open', <String>[fileLocation], runInShell: true); } }
STEP 3: Initialize the SfDataGrid widget with all the required properties. Create the GlobalKey using the SfDataGridState and set the key to the DataGrid.
Import the save_file_mobile_desktop and save_file_web.dart files.
Call the exportToPdfDocument method from MaterialButton’s’ onPressed callback and pass the exported pdf’s’ bytes to saveAndLaunchFile method.
import 'helper/save_file_mobile_desktop.dart' if (dart.library.html) 'helper/save_file_web.dart' as helper; List<Employee> employees = <Employee>[]; late EmployeeDataGridSource employeeDataGridSource; final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>(); @override void initState() { super.initState(); employees = getEmployeeData(); employeeDataGridSource = EmployeeDataGridSource(employeeData: employees); } Future<void> exportDataGridToPdf() async { final PdfDocument document = _key.currentState!.exportToPdfDocument(fitAllColumnsInOnePage: true); final List<int> bytes = document.save(); await helper.saveAndLaunchFile(bytes, 'DataGrid.pdf'); document.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid Export')), body: Column(children: <Widget>[ Container( margin: const EdgeInsets.all(12.0), child: Row(children: <Widget>[ SizedBox( height: 40.0, width: 150.0, child: MaterialButton( color: Colors.blue, child: const Center( child: Text('Export to PDF, style: TextStyle(color: Colors.white))), onPressed: exportDataGridToPdf)) ])), Expanded( child: SfDataGrid( key: _key, source: employeeDataGridSource, columns: <GridColumn>[ GridColumn( columnName: 'ID', label: Container( padding: const EdgeInsets.all(16.0), alignment: Alignment.center, child: const Text('ID'))), GridColumn( columnName: 'Name', label: Container( padding: const EdgeInsets.all(8.0), alignment: Alignment.center, child: const Text('Name'))), GridColumn( columnName: 'Designation', label: Container( padding: const EdgeInsets.all(8.0), alignment: Alignment.center, child: const Text('Designation', overflow: TextOverflow.ellipsis))), GridColumn( columnName: 'Salary', label: Container( padding: const EdgeInsets.all(8.0), alignment: Alignment.center, child: const Text('Salary'))) ])) ])); }
You can go through this UG link, to know more about the PDF exporting.
You can download this example oin GitHub.
Conclusion
I hope you enjoyed learning about how to export Flutter DataTable to PDF document and save it as file.
You can refer to our Flutter DataGrid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!