SameJall
SameJall

Reputation: 113

Generating PDF file with Images in flutter

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

Upvotes: 1

Views: 4357

Answers (2)

SameJall
SameJall

Reputation: 113

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

Upvotes: 0

hasan karaman
hasan karaman

Reputation: 1430

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

Upvotes: 1

Related Questions