Using this code I'm unable to call an image from the media assets into a custom action. The exception thrown is "unable to load asset: "ADM1007.png".
Future<String> generateReimbursementForm(
String expenseSupplier,
String expenseDetails,
String dateIncurred,
bool gst,
String gstExclusive,
String expenseTotal,
String signature,
) async {
try {
// Create a new PDF document
final pdfDoc = pw.Document();
// Load image
final imageData = await rootBundle.load('assets/ADM1007.png');
print('Loaded image length: ${imageData.lengthInBytes} bytes');
final backgroundImage = pw.MemoryImage(imageData.buffer.asUint8List());
pdfDoc.addPage(pw.Page(
pageFormat: PdfPageFormat.a4.landscape.copyWith(
marginLeft: 0,
marginRight: 0,
marginTop: 0,
marginBottom: 0,
),
build: (pw.Context context) {
return pw.Stack(children: [
// Background image fills the entire page.
pw.Container(
width: PdfPageFormat.a4.width,
height: PdfPageFormat.a4.height,
child: pw.Image(
backgroundImage,
fit: pw.BoxFit.cover,
),
),
// Overlay the supplier name at 49.89, 124.52
pw.Positioned(
left: 49.89,
top: 124.52,
child: pw.Text(
expenseSupplier,
style: pw.TextStyle(fontSize: 12),
),
),
// Overlay the details at 225.05, 124.52.
pw.Positioned(
left: 225.05,
top: 124.52,
child: pw.Text(
expenseDetails,
style: pw.TextStyle(fontSize: 12),
),
),
// Overlay the date incurred at 472.6, 124.14
pw.Positioned(
left: 472.6,
top: 124.14,
child: pw.Text(
dateIncurred,
style: pw.TextStyle(fontSize: 12),
),
),
// Overlay the gstExclusive at 552.87, 124.52
pw.Positioned(
left: 552.87,
top: 124.52,
child: pw.Text(
gstExclusive,
style: pw.TextStyle(fontSize: 12),
),
),
// Overlay the expenseTotal at 612.88, 123.39
pw.Positioned(
left: 612.88,
top: 123.39,
child: pw.Text(
expenseTotal,
style: pw.TextStyle(fontSize: 12),
),
),
// Overlay the signature at 225.05, 438.65
pw.Positioned(
left: 225.05,
top: 438.65,
child: pw.Text(
signature,
style: pw.TextStyle(fontSize: 12),
),
),
]);
}));
// Save the PDF document as bytes.
final pdfBytes = await pdfDoc.save();
// On web, use dart:html to trigger a file download.
final blob = html.Blob([pdfBytes], 'application/pdf');
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
..href = url
..style.display = 'none'
..download = 'expense_claim.pdf';
html.document.body?.append(anchor);
anchor.click();
anchor.remove();
html.Url.revokeObjectUrl(url);
// Return a message indicating that the download was triggered.
return 'Download triggered';
} catch (e) {
return 'Error: $e';
}
}