How to convert a whole flutter Screen to pdf?

Viewed 5165

I have a flutter E-commerce App which has a orderDetails page , I want to convert the whole page to pdf using flutter pdf package, as it would be more convinent because the data is retrived from FirebaseFirestore. Is there a way around I can achieve this ?

sub: I want to convert the whole flutter screen to pdf using this library

3 Answers

You can capture the screen using this package screenshot

then add that image to pdf document and save it

import 'dart:io';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;

Future getPdf(Uint8List screenShot) async {
  pw.Document pdf = pw.Document();
  pdf.addPage(
    pw.Page(
      pageFormat: PdfPageFormat.a4,
      build: (context) {
        return pw.Expanded(
          child: pw.Image(PdfImage.file(pdf.document, bytes: screenShot), fit: pw.BoxFit.contain)
        );
      },
    ),
  );
  File pdfFile = File('Your path + File name');
  pdfFile.writeAsBytesSync(pdf.save());
}

full details: load dependencies in pubspec.yaml:

 screenshot: 
  share_plus: 
  path_provider:
  permission_handler:

import packages in your dart file:

import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import 'package:permission_handler/permission_handler.dart';

  shareImage() async {

    final uint8List = await screenshotController.capture();
    String tempPath = (await getTemporaryDirectory()).path;
    String fileName ="myFile";
    if (await Permission.storage.request().isGranted) {
      File file = await File('$tempPath/$fileName.png').create();
      file.writeAsBytesSync(uint8List);
      await Share.shareFiles([file.path]);
    }
  }

and call shareImage() on any place:

 GestureDetector(
   onTap: (){ shareImage();},
   child: ........,
  ),

remember to wrap your desire widget in:

Screenshot(
    controller: screenshotController,
    child: Text("This text will be captured as image"),
),
  newest solution will be
    shareImage() async {
    final uint8List = await screenshotController.capture();
        String tempPath = (await getTemporaryDirectory()).path;
    String fileName =" ";>>>>>your file name between ""
    File file = await File('$tempPath/$fileName" }.png').create();
    file.writeAsBytesSync(uint8List!);
     await Share.shareFiles([file.path]);
    }
Related