Making PDF with Flutter

You might need to construct a detailed view that doesn’t fit your device size when building a mobile app. In some circumstances, you can view your details in a pdf file. Let’s look at how to create a pdf view using the data you have in Flutter.

To make things simpler, we can use packages developed by the flutter community.

Install the following packages in the most recent versions to get started. These are the variations I employed.

pdf: ^1.3.24
flutter_full_pdf_viewer: ^1.0.6
path_provider: ^1.5.1

Create a PdfViewerPage for the specified path using the flutter_full_pdf_viewer.

import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';

class PdfViewerPage extends StatelessWidget {
  final String path;
  const PdfViewerPage({Key key, this.path}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
      path: path,
    );
  }
}

Your PDF material can then be created. A collection of widgets to build the pdf’s content are provided by the package “package:pdf/widgets.dart”. You may create a pdf for the data from an API request in addition to creating static tables and paragraphs. The PDF/widgets’ widgets are not exactly the same as the material widgets. You can examine these widgets in more detail to discover their capabilities and distinctions.

import 'package:flutterexamples/screens/pdf_creation/pdf_viewer_page.dart';
import 'package:pdf/pdf.dart';
import 'dart:io';
import 'package:pdf/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart' as material;

flutterView(context) async {
  final Document pdf = Document();

  pdf.addPage(MultiPage(
      pageFormat:
      PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
      crossAxisAlignment: CrossAxisAlignment.start,
      header: (Context context) {
        if (context.pageNumber == 1) {
          return null;
        }
        return Container(
            alignment: Alignment.centerRight,
            margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            decoration: const BoxDecoration(
                border:
                BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)),
            child: Text('Flutter',
                style: Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },
      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: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text('Flutter', textScaleFactor: 2),
                  PdfLogo()
                ])),
        Header(level: 1, text: 'What is Flutter?'),
        Paragraph(
            text:
            'Flutter is an open source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase.'),
        Paragraph(
            text:
            'Flutter code compiles to ARM or Intel machine code as well as JavaScript, for fast performance on any device.'),
        Header(level: 1, text: 'Set up an editor'),
        Paragraph(
            text:
            'You can build apps with Flutter using any text editor combined with our command-line tools. However, we recommend using one of our editor plugins for an even better experience. These plugins provide you with code completion, syntax highlighting, widget editing assists, run & debug support, and more.'),
        Paragraph(
            text:
            'Follow the steps below to add an editor plugin for Android Studio, IntelliJ, VS Code, or Emacs. If you want to use a different editor, that OK, skip ahead to the next step: Test drive.'),
        Padding(padding: const EdgeInsets.all(10)),
        Table.fromTextArray(context: context, data: const <List<String>>[
          <String>['Demo', 'Demo', 'Demo'],
          <String>['Test', 'Test', 'Test'],
          <String>['Test', 'Test', 'Test'],

        ]),
      ]));
  //save PDF

  final String dir = (await getApplicationDocumentsDirectory()).path;
  final String path = '$dir/report.pdf';
  final File file = File(path);
  await file.writeAsBytes(pdf.save());
  material.Navigator.of(context).push(
    material.MaterialPageRoute(
      builder: (_) => PdfViewerPage(path: path),
    ),
  );
}

You can use it like this if it’s just one page.

pdf.addPage(Page(
      pageFormat: PdfPageFormat.a4,
      build: (Context context) {
        return Center(
          child: Text("PDF"),
        ); // Center
      }));

Add the following code line within the flutterView to save and open the pdf. further import content. use the navigator by darting. If you install the aforementioned packages after launching the project, you must restart them because the packages won’t function correctly during a hot reload or hot restart.

import 'package:flutter/material.dart' as material;

final String dir = (await getApplicationDocumentsDirectory()).path;
  final String path = '$dir/report.pdf';
  final File file = File(path);
  await file.writeAsBytes(pdf.save());
  material.Navigator.of(context).push(
    material.MaterialPageRoute(
      builder: (_) => PdfViewerPage(path: path),
    ),
  );

See the view by calling the PDF view for an on-click function. Apply the view’s UI and content updates.

body: Center(
        child:Container(
            margin: EdgeInsets.only(
                top: 30),
            height: 40,
            child: RaisedButton(
                shape: new RoundedRectangleBorder(
                  borderRadius:
                  new BorderRadius.circular(5.0),
                ),
                child: Text(
                  'Get PDF',
                  style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold),
                ),
                color: Colors.blue,
                onPressed:(){
                  flutterView(context);
                }
            )
        )
      )

I hope this article has given you some useful knowledge.

Submit a Comment

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

Subscribe

Select Categories