0

I'm creating a pdf with flutter using a 'pdf' package. So I want to insert an image in pdf. The problem is that then I don't know how to load an image from assets in the 'Image' package which is recommended to use in the 'pdf' package. Refrence:https://pub.dev/packages/pdf :pdf package refrence and https://pub.dev/packages/image: image package refrence

I have tried some code but none work pdf.dart

import 'package:image/image.dart' as imgs;
final img1 = imgs.decodeImage(File('assets/logo.png').readAsBytesSync());
Image(PdfImage(
                      pdf.document,
                      height: 20,
                      width: 20,
                      image: img1.data.buffer.asUint8List(),
                    ))

I have image in assests folder in project and I also have it in pubspec.yaml file

I am expecting to load the image from the assets folder using the 'image' package. Or is there another way to load an image in 'pdf' package.

Some of the error when I use the above code:

E/PDFView (13223): load pdf error
E/PDFView (13223): java.io.FileNotFoundException: No such file or directory
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Ankit Mishra
  • 13
  • 1
  • 3

1 Answers1

0

See this answer on how to load image from asset bundle. File('assets/logo.png') will attempt to find that file on the phone's filesystem which is not where your asset bundle is.


Alternatively if you also have the printing package installed:

import 'package:printing/printing.dart';
import 'package:flutter/material.dart' show AssetImage;

final pdf = Document(deflate: zlib.encode);

PdfImage logoImage = await pdfImageFromImageProvider(
  pdf: pdf.document,
  image: AssetImage('assets/logo.png'),
);

Wrap it with the Image widget from package:pdf/widgets.dart then add it to your document:

pdf.addPage(
  MultiPage(
    header: Image(logoImage),
    build: Container(),
    footer: Container(),
  ),
);
Swift
  • 3,250
  • 1
  • 19
  • 35
  • 1
    I'm using ``package:pdf/pdf.dart`` does it also have pdfImageFromImageProvider().what should I do to use in pdf/pdf.dart package – Ankit Mishra Jul 20 '19 at 01:55
  • See [this answer](https://stackoverflow.com/a/47125727/6300600) on how to load image from asset bundle. `File('assets/logo.png')` will attempt to find that file on the phone's filesystem which is not where your asset bundle is – Swift Jul 20 '19 at 02:51
  • When I add 'printing' package and run app then it is showing error :```[ERROR:flutter/lib/ui/painting/codec.cc(207)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.``` – Ankit Mishra Jul 20 '19 at 05:30