1

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

6
  • Did you declare image in pubspec.yaml? Commented May 27, 2021 at 9:38
  • Yes, also I added the Image to the App screen to make sure that the image is there. Commented May 27, 2021 at 9:47
  • you need to write the path as assets/images/header.png. Commented May 27, 2021 at 13:17
  • 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')).readAsBytesSync()); Future writeOnPdf() async { pdf.addPage(pw.Page( pageFormat: PdfPageFormat.a4,``` the same error Commented May 27, 2021 at 14:11
  • 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')).readAsBytesSync()); pdf.addPage(pw.Page( pageFormat: PdfPageFormat.a4, a different error will happen but the screen will be white only Commented May 27, 2021 at 14:12

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I already added the images folder to pubseps.yaml... but the same result.
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.
I attached the pubspec.yaml.. all aligned & the routes are done already correctly
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.