Generate pdf file by pressing on button

247 Views Asked by At

When I call the createPDF function nothing happens. I use my phone as emulator and its Android.

This is the code:

import 'dart:typed_data'; 
import 'package:flutter/services.dart'; 
import 'package:open_file/open_file.dart'; 
import 'package:path_provider/path_provider.dart'; 
import 'package:pdf/widgets.dart' as pw ; 

class PdfView { 
 PdfView(); 
 static void createPDF()async { 
  String path = (await getApplicationDocumentsDirectory()).path; 
  File file = File('${path}my_resume.pdf'); 
  final font = await rootBundle.load("assets/fonts/Poppins/Poppins-Italic.ttf"); 
  final ttf = pw.Font.ttf(font); 
  final pdf = pw.Document(); 
  pdf.addPage(_addPage(font :ttf,size: 50)); 
  Uint8List bytes = await pdf.save(); 
  await file.writeAsBytes(bytes); 
  await OpenFile.open(file.path); 
 } 

 static pw.Page _addPage({required pw.Font font,required double size}){ 
  pw.TextStyle? style=  pw.TextStyle(font: font,fontSize: size); 
  return pw.Page( 
      build: (pw.Context context) { 
        return pw.Center( 
        child: pw.Text('Hello World!',style: style), 
      ); 
 });  
 } 
}

I tried make the createPDF function future and async onpressed of the button that after press on it the PDF created but also nothing happened.

1

There are 1 best solutions below

2
mc100p On

This solution works for both android and iOS - please follow me on instagram - https://www.instagram.com/mcbflutter/

took it a step further and even made a table to show a few features...

import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:open_file_plus/open_file_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/material.dart';
import 'package:test/Custom_row.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
          onPressed: () => createPDF(), child: const Icon(Icons.download)),
      appBar: AppBar(
        title: const Text("PDF Downloader"),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
    );
  }

  Future<Uint8List?> createPDF() async {
    final pdf = pw.Document();

    List headers = [
      "Property",
      "Value",
    ];

    List values = [
      CustomRow(name: "name", value: "value"),
      CustomRow(name: "name", value: "value"),
      CustomRow(name: "name", value: "value"),
    ];

    final data = values.map((e) => [e.name, e.value]).toList();

    pdf.addPage(
      pw.MultiPage(
        build: (context) => [
          pw.SizedBox(height: 100),
          pw.Text(
            "Dart is awesome",
            style: pw.TextStyle(fontWeight: pw.FontWeight.bold),
          ),
          pw.Text(
            "Hello World",
            style: pw.TextStyle(fontWeight: pw.FontWeight.bold),
          ),
          pw.SizedBox(height: 100),
          pw.TableHelper.fromTextArray(
              data: data,
              headers: headers,
              tableWidth: pw.TableWidth.max,
              border: pw.TableBorder.all(color: PdfColors.black, width: 1.0))
        ],
      ),
    );

    List<int> bytes = await pdf.save();
    saveAndLaunchFile(bytes, 'PDF Document.pdf');
    return pdf.save();
  }

  Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
    bool dirDownloadExists = true;
    String androidDirectory;
    androidDirectory = '/storage/emulated/0/Download/';

    dirDownloadExists = await Directory(androidDirectory).exists();

    if (dirDownloadExists) {
      androidDirectory = "/storage/emulated/0/Download";
    } else {
      androidDirectory = "/storage/emulated/0/Downloads";
    }

    final path = Platform.isAndroid
        ? androidDirectory
        : (await getApplicationDocumentsDirectory()).path;

    final file = File('$path/$fileName');
    await file.writeAsBytes(bytes, flush: true);
    OpenFile.open('$path/$fileName');
  }
}

add a custom file for the table

enter image description here

configuration for iOS

add these two keys to your info.plist

<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>

enter image description here

for android - Configure your android manifest

enter image description here

essentially it will look like this - lines 2 and 36 to 46

enter image description here

result: enter image description here