Tables in Flutter PDF library

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:

12dependencies:  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();
}
Hey folks, I'm Vivek Kumar Pandey, a software engineer with a passion for crafting elegant solutions to complex problems. From the bustling streets of Mumbai to the heart of Bangalore's tech scene, I've journeyed through the world of programming, leaving my mark one line of code at a time. Join me as I continue to explore, innovate, and push the boundaries of what's possible in the digital realm.

Related Posts

CERTIFICATE_VERIFY_FAILED Error while performing a POST Request In Flutter

When Sending a post request in Dart. It is giving a response when We test it on API testing tools such as Postman. But when We run…

Get Current Location In Flutter

Hello friends, today in this article I am going to teach you how to get user’s current location in flutter. Its video tutorial is also on my YouTube…

Best Way To Use SharedPreferences In Flutter

In Flutter’s mobile application, if we have to store some value permanently in the mobile device itself, while the user does not clear the data of the…

This Post Has One Comment

  1. Наша команда квалифицированных исполнителей проштудирована предоставить вам перспективные приемы, которые не только обеспечат надежную протекцию от холодных воздействий, но и преподнесут вашему домашнему пространству оригинальный вид.
    Мы работаем с современными материалами, сертифицируя долгий период службы и прекрасные итоги. Изолирование фронтонов – это не только экономия ресурсов на подогреве, но и ухаживание о экологии. Энергосберегающие подходы, какие мы применяем, способствуют не только зданию, но и сохранению природной среды.
    Самое важное: Сколько стоит сделать фасад дома с утеплением у нас начинается всего от 1250 рублей за квадратный метр! Это доступное решение, которое переделает ваш домашний уголок в реальный теплый корнер с скромными тратами.
    Наши труды – это не только утепление, это постройка помещения, в где любой элемент символизирует ваш персональный модель. Мы берем во внимание все твои требования, чтобы переделать ваш дом еще еще больше комфортным и привлекательным.
    Подробнее на http://www.ppu-prof.ru
    Не откладывайте занятия о своем корпусе на потом! Обращайтесь к профессионалам, и мы сделаем ваш домик не только тепличным, но и по последней моде. Заинтересовались? Подробнее о наших делах вы можете узнать на веб-ресурсе. Добро пожаловать в мир спокойствия и высоких стандартов.

Leave a Reply

Your email address will not be published. Required fields are marked *