David PHAM-VAN

Add WidgetWraper ImageProvider

# Changelog
## 4.0.1
## 4.1.0
- Remove useless files
- Add WidgetWraper ImageProvider and deprecate wrapWidget()
## 4.0.0
... ...
... ... @@ -15,13 +15,16 @@
*/
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
/// Wrap a Flutter Widget identified by a GlobalKey to a PdfImage.
@Deprecated('Use WidgetWraper.fromKey() instead')
Future<PdfImage> wrapWidget(
PdfDocument document, {
@required GlobalKey key,
... ... @@ -40,3 +43,85 @@ Future<PdfImage> wrapWidget(
return PdfImage(document,
image: imageData, width: image.width, height: image.height);
}
/// ImageProvider that draws a Flutter Widget on a PDF document
class WidgetWraper extends pw.ImageProvider {
WidgetWraper._(
this.bytes,
int width,
int height,
PdfImageOrientation orientation,
double dpi,
) : super(width, height, orientation, dpi);
/// Wrap a Flutter Widget identified by a GlobalKey to an ImageProvider.
///
/// Use it with a RepaintBoundary:
/// ```
/// final rb = GlobalKey();
///
/// @override
/// Widget build(BuildContext context) {
/// return RepaintBoundary(
/// key: rb,
/// child: FlutterLogo()
/// );
/// }
///
/// Future<Uint8List> _generatePdf(PdfPageFormat format) async {
/// final pdf = pw.Document();
///
/// final image = await WidgetWraper.fromKey(key: rb);
///
/// pdf.addPage(
/// pw.Page(
/// build: (context) {
/// return pw.Center(
/// child: pw.Image(image),
/// );
/// },
/// ),
/// );
///
/// return pdf.save();
/// }
/// ```
static Future<WidgetWraper> fromKey({
@required GlobalKey key,
int width,
int height,
double pixelRatio = 1.0,
PdfImageOrientation orientation,
double dpi,
}) async {
assert(key != null);
assert(pixelRatio != null && pixelRatio > 0);
final RenderRepaintBoundary wrappedWidget =
key.currentContext.findRenderObject();
final image = await wrappedWidget.toImage(pixelRatio: pixelRatio);
final byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
final imageData = byteData.buffer.asUint8List();
return WidgetWraper._(
imageData,
image.width,
image.height,
orientation ?? PdfImageOrientation.topLeft,
dpi,
);
}
/// The image data
final Uint8List bytes;
@override
PdfImage buildImage(pw.Context context, {int width, int height}) {
return PdfImage(
context.document,
image: bytes,
width: width ?? this.width,
height: height ?? this.height,
orientation: orientation,
);
}
}
... ...
... ... @@ -4,7 +4,7 @@ description: Plugin that allows Flutter apps to generate and print documents to
homepage: https://github.com/DavBfr/dart_pdf/tree/master/printing
repository: https://github.com/DavBfr/dart_pdf
issue_tracker: https://github.com/DavBfr/dart_pdf/issues
version: 4.0.1
version: 4.1.0
environment:
sdk: ">=2.3.0 <3.0.0"
... ...