Generating PDF file with Images in flutter

1,436

Solution 1

I found the solution, I contacted the flutter package maker & he was king enough to guide me to what to do, first he guided me to created the following function out

  final data = await rootBundle.load('images/$name');
  return data.buffer.asUint8List();
}

Then also he guided me to move the PDF creation method from statless to statfull and in the writePDF() to add the image as the below code

    final image = pw.MemoryImage(await _readImageData('header.png'));

now the images are shown in the PDF file with no problems

Solution 2

There is no path to the official file you are trying to add. You can get the file path by right clicking on the picture in the file and clicking copy relative path. then if you are using windows, you can use the file path after converting the '' \ '' s to '/' and putting them under assets in pubseps.yaml.

enter image description here

Share:
1,436
SameJall
Author by

SameJall

Updated on November 23, 2022

Comments

  • SameJall
    SameJall over 1 year

    I need some help please... I am trying to generate a PDF file (text & Images) using flutter, so I used the PDF package pdf: ^3.3.0, the text is shown once I generated the PDF file but every time I try to insert an image the below error is showing...even the image is loading in the main screen... the error is enter image description here

    my code is as the following:

    import 'dart:io';
    import 'dart:typed_data';
    
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:pdf/pdf.dart';
    import 'package:pdf/widgets.dart' as pw;
    import 'package:duct_sizer/pdf_preview_screen.dart';
    
    class MyHomePage extends StatelessWidget {
      final pdf = pw.Document();
      final image = pw.MemoryImage(File('images/duct.jpg').readAsBytesSync());
    
      writeOnPdf() async {
        // final profileImage = pw.MemoryImage(
        //   (await rootBundle.load('images/duct.jpg')).buffer.asUint8List(),
        // );
    
        pdf.addPage(pw.MultiPage(
          pageFormat: PdfPageFormat.a5,
          margin: pw.EdgeInsets.all(32),
          build: (pw.Context context) {
            return <pw.Widget>[
              pw.Header(level: 0, child: pw.Text("Easy Approach Document")),
              pw.Paragraph(
                  text:
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada fames ac turpis egestas sed tempus urna. Quisque sagittis purus sit amet. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Ipsum dolor sit amet consectetur adipiscing elit pellentesque. Viverra justo nec ultrices dui sapien eget mi proin sed."),
              pw.Paragraph(
                  text:
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada fames ac turpis egestas sed tempus urna. Quisque sagittis purus sit amet. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Ipsum dolor sit amet consectetur adipiscing elit pellentesque. Viverra justo nec ultrices dui sapien eget mi proin sed."),
              pw.Header(level: 1, child: pw.Text("Second Heading")),
              pw.Image(image),
              pw.Paragraph(
                  text:
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada fames ac turpis egestas sed tempus urna. Quisque sagittis purus sit amet. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Ipsum dolor sit amet consectetur adipiscing elit pellentesque. Viverra justo nec ultrices dui sapien eget mi proin sed."),
              pw.Paragraph(
                  text:
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada fames ac turpis egestas sed tempus urna. Quisque sagittis purus sit amet. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Ipsum dolor sit amet consectetur adipiscing elit pellentesque. Viverra justo nec ultrices dui sapien eget mi proin sed."),
              pw.Paragraph(
                  text:
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada fames ac turpis egestas sed tempus urna. Quisque sagittis purus sit amet. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Ipsum dolor sit amet consectetur adipiscing elit pellentesque. Viverra justo nec ultrices dui sapien eget mi proin sed."),
            ];
          },
        ));
      }
    
      Future savePdf() async {
        final bytes = await pdf.save();
    
        Directory documentDirectory = await getApplicationDocumentsDirectory();
    
        String documentPath = documentDirectory.path;
    
        File file = File("$documentPath/example.pdf");
    
        file.writeAsBytesSync(bytes);
      }
    
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("PDF Flutter"),
          ),
    
          body: Container(
            width: double.infinity,
            height: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  "PDF TUTORIAL",
                  style: TextStyle(fontSize: 34),
                ),
                Image(
                  image: AssetImage('images/header.png'),
                ),
              ],
            ),
          ),
    
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              writeOnPdf();
              await savePdf();
    
              Directory documentDirectory =
                  await getApplicationDocumentsDirectory();
    
              String documentPath = documentDirectory.path;
    
              String fullPath = "$documentPath/example.pdf";
              print(fullPath);
    
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => PDFPreviewScreen(
                            path: fullPath,
                          )));
            },
            child: Icon(Icons.save),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    }
    

    and the PDF preview page is

    import 'package:flutter/material.dart';
    import 'package:flutter_full_pdf_viewer/flutter_full_pdf_viewer.dart';
    import 'package:flutter_full_pdf_viewer/full_pdf_viewer_plugin.dart';
    import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
    
    class PDFPreviewScreen extends StatelessWidget {
      final String path;
    
      PDFPreviewScreen({this.path});
    
      @override
      Widget build(BuildContext context) {
        return PDFViewerScaffold(
          path: path,
        );
      }
    }
    

    please assets me

    This is a new update on the pubspec.yaml file which shows the dependencies & the images identifications enter image description here also As I said earlier the photo is displayed in the main App direct, but the the PDF this error will happen

    • Xihuny
      Xihuny almost 3 years
      Did you declare image in pubspec.yaml?
    • SameJall
      SameJall almost 3 years
      Yes, also I added the Image to the App screen to make sure that the image is there.
    • Xihuny
      Xihuny almost 3 years
      you need to write the path as assets/images/header.png.
    • SameJall
      SameJall almost 3 years
      Still Same Issue if I kept the code ``` class MySecondHomePage extends StatelessWidget { final pdf = pw.Document(); final image = pw.MemoryImage((File('assets/images/duct.jpg')).readAsBytesS‌​ync()); Future writeOnPdf() async { pdf.addPage(pw.Page( pageFormat: PdfPageFormat.a4,``` the same error
    • SameJall
      SameJall almost 3 years
      but if I changed the code to class MySecondHomePage extends StatelessWidget { final pdf = pw.Document(); Future writeOnPdf() async { final image = pw.MemoryImage((File('assets/images/duct.jpg')).readAsBytesS‌​ync()); pdf.addPage(pw.Page( pageFormat: PdfPageFormat.a4, a different error will happen but the screen will be white only
    • SameJall
      SameJall almost 3 years
      the new errorE/flutter (18539): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/images/duct.jpg' (OS Error: No such file or directory, errno = 2) E/flutter (18539): #0 _File.throwIfError (dart:io/file_impl.dart:635:7)
  • SameJall
    SameJall almost 3 years
    I already added the images folder to pubseps.yaml... but the same result.
  • hasan karaman
    hasan karaman almost 3 years
    You made the addition wrong. You may have made a mistake on the page. The part where you add pubsepc.yaml must be properly aligned. Please pay attention to her.
  • hasan karaman
    hasan karaman almost 3 years
  • SameJall
    SameJall almost 3 years
    I attached the pubspec.yaml.. all aligned & the routes are done already correctly