Monday, 27 July 2020

create pdf file in flutter


dependencies:
  pdf: ^1.9.0

CreatePdf.dart 

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image/image.dart';
import 'package:movements/Utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;


class CreatePdf extends StatefulWidget {
  @override  _CreatePdfState createState() => _CreatePdfState();
}

class _CreatePdfState extends State<CreatePdf> {
  @override  void initState() {
    // TODO: implement initState    super.initState();
  }

  @override  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Create PDF"),
        elevation: .1,
      ),
      body: Center(
        child: Container(
          child: FlatButton(
              onPressed: () {
                createPdf();
              },
              child: Text("Create PDF")),
        ),
      ),
    );
  }


  Future createPdf() async {
    final pdf = pw.Document();


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

    var number = Utils.getRandomNumber(4);
    final output =
        await getExternalStorageDirectory(); // use the [path_provider (https://pub.dartlang.org/packages/path_provider) library:    final file = File("${output.path}/example" + number.toString() + ".pdf");
    await file.writeAsBytes(pdf.save());
  }
}

2 comments: