Skip to content

Network Image

David PHAM-VAN edited this page Jan 20, 2021 · 2 revisions

In your pubspec.yaml, use:

dependencies:
  flutter:
    sdk: flutter
  pdf:
  printing:
  path_provider:

And create this two functions:

Future<pw.ImageProvider> networkImage(
  String url, {
  bool cache = true,
  PdfImageOrientation orientation,
  double dpi,
}) async {
  final img = await download(url, cache: cache);
  return pw.MemoryImage(img, orientation: orientation, dpi: dpi);
}

Future<Uint8List> download(
  String url, {
  bool cache = true,
}) async {
  File file;
  if (cache) {
    final tmp = await pp.getTemporaryDirectory();
    file = File('${tmp.path}/${url.hashCode}');
    if (file.existsSync()) {
      return await file.readAsBytes();
    }
  }

  print('Downloading $url');
  final client = HttpClient();
  final request = await client.getUrl(Uri.parse(url));
  final response = await request.close();
  final builder = await response.fold(
      BytesBuilder(), (BytesBuilder b, List<int> d) => b..add(d));
  final List<int> data = builder.takeBytes();

  if (cache) {
    await file.writeAsBytes(data);
  }
  return Uint8List.fromList(data);
}

Then they are used like this:

  Future<Uint8List> _generatePdf(PdfPageFormat format, String title) async {
    final pdf = pw.Document();

    final img = await networkImage('https://upload.wikimedia.org/wikipedia/commons/a/a9/Example.jpg');

    pdf.addPage(
      pw.Page(
        pageFormat: format,
        build: (context) {
          return pw.Center(
            child: pw.Image(img),
          );
        },
      ),
    );

    return pdf.save();
  }
Clone this wiki locally