fromKey static method
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();
}
Implementation
static Future<WidgetWraper> fromKey({
required GlobalKey key,
int? width,
int? height,
double pixelRatio = 1.0,
PdfImageOrientation? orientation,
double? dpi,
}) async {
assert(pixelRatio > 0);
final wrappedWidget =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
final image = await wrappedWidget.toImage(pixelRatio: pixelRatio);
final byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
if (byteData == null) {
return WidgetWraper._(
Uint8List(0),
0,
0,
PdfImageOrientation.topLeft,
dpi,
);
}
final imageData = byteData.buffer.asUint8List();
return WidgetWraper._(
imageData,
image.width,
image.height,
orientation ?? PdfImageOrientation.topLeft,
dpi,
);
}