Hello Guys’ in this tutorial, I will teach you how to create a dynamically table in flutter pdf. I will use a plugin for this. Many times it happens that some records created pdf have to be displayed in tabular form and the record is dynamically as if you are gating those records from another server, here you have to use the same records in the server where you work.
Here are two things to focus on
1st) Header
2nd) Table records
So first we understand that the header will also be of two types here. One is the header of the table and the other is the header of the pdf. So let’s understand both of them one by one, before that people have to get a flutter library.
First you have to add this to your package’s pubspec.yaml file:
12 | dependencies: pdf: ^3.0.1 |
When I am making this tutorial, this is the latest version, you can use the latest version from here.
Now in your Dart code, you have to import these libraries :
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';
Here I write some code in main.dart where you will have a simple floating button, you can see below. I named that button pdf.
/// Flutter code for FloatingActionButton
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
String exportfilename ="pdf";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Floating Action Button Label'),
),
body: const Center(
child: Text('Press the button with a label below!'),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
<strong>reportView(HeaderListData,Formdata,MappingData,ExtFilenameasString,exportfilename);</strong>
},
label: const Text('PDF'),
icon: const Icon(Icons.thumb_up),
backgroundColor: Colors.pink,
),
);
}
}
here you can see onPressed method in i use a method called reportView and also send some parameter here you can use your records in json formet like : Header Column name , records for table, pdf name etc.
Now I create another dart file named pdf.dart. whenever a user clicks on the floating button, this page will be called. And here pdf will be generated see full code .
Full Code
pdf.dart
import 'package:ext_storage/ext_storage.dart';
import 'package:pdf/pdf.dart';
import 'dart:io';
import 'package:pdf/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sweetalert/sweetalert.dart';
reportView(
header, formdata, MappingData, ExtFilenameasString, exportfilename) async {
final Document pdf = Document();
print(header);
List<List<String>> DataList = new List();
List<String> headerList = new List();
for (var i = 0; i < header.length; i++) {
headerList.add(header[i]['sTitle']);
}
for (int i = 0; i < formdata.length; i++) {
var k = 0;
List<String> recind = [];
formdata[i].forEach((key, value) {
recind.add(formdata[i][MappingData[k]]);
k++;
});
DataList.add(recind);
}
DataList.insert(0, headerList);
print(DataList);
// print(headerList);
pdf.addPage(MultiPage(
// pageFormat:PdfPageFormat.letter.copyWith(marginBottom: 1 * PdfPageFormat.cm),
pageFormat: PdfPageFormat.a3,
crossAxisAlignment: CrossAxisAlignment.start,
header: (Context context) {
if (context.pageNumber == 1) {
return null;
}
return Container(
// color: PdfColors.blue,
// alignment: Alignment.centerRight,
margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
decoration: BoxDecoration(
color: PdfColors.blue,
// border:BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)
border: Border.all(color: PdfColors.blueAccent)),
child:Align(
alignment: Alignment.center,
child: Text('Pdf Genrator In tabular form',
textAlign: TextAlign.center,
textScaleFactor: 2,
style: TextStyle(color: PdfColors.white)
),
)
);
},
footer: (Context context) {
return Container(
alignment: Alignment.centerRight,
margin: const EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
child: Text('Page ${context.pageNumber} of ${context.pagesCount}',
style: Theme.of(context)
.defaultTextStyle
.copyWith(color: PdfColors.grey)));
},
build: (Context context) => <Widget>[
Header(
level: 0,
child: Container(
margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
decoration: BoxDecoration(
color: PdfColors.blue,
// border:BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)
border: Border.all(color: PdfColors.blueAccent)),
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
child:Align(
alignment: Alignment.center,
child: Text('Pdf Genrator In tabular form',
textAlign: TextAlign.center,
textScaleFactor: 2,
style: TextStyle(color: PdfColors.white)
),
)
)
),
Header(level: 1, text: "$exportfilename List"),
Padding(padding: const EdgeInsets.all(10)),
Table.fromTextArray(context: context, data: DataList),
]));
//save PDF
//Save and dispose the PDF document
String path = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
print(path);
String Filepath = '$path/$ExtFilenameasString.pdf';
File file = await File(Filepath);
await file.writeAsBytes(await pdf.save());
// document.dispose();
}