I am currently generating a report using the pdf syncfusion when an Elevated Button is clicked. I know how to import string data from firebase into the pdf, but not sure how to do it for image.
I want to add in here: -
contentRow1.cells[2].style.backgroundImage = ??????
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:myasset_login/screens/stainspection_screen.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
@override
State createState() =>
_ReportStationInspectionScreenState();
}
class _ReportStationInspectionScreenState
extends State<ReportStationInspectionScreen> {
String time = '?';
DateTime dateTimeEsc = (DateTime.now());
var functionality;
var totalUnits;
var totalOOS;
var totalInService;
XFile? pickedImage;
Map<String, dynamic>? image;
Map<String, dynamic>? imageFSFaucet;
DateTime? lastDateTime;
String? commentsFSFaucet;
bool isButtonActiveTotal = false;
bool isButtonActiveOOS = false;
@override
void initState() {
super.initState();
_totalUnitsController.addListener(() {
setState(() {
isButtonActiveTotal = _totalUnitsController.text.isNotEmpty;
});
});
_totalOOSController.addListener(() {
setState(() {
isButtonActiveOOS = _totalOOSController.text.isNotEmpty;
});
});
}
Future<List<Map<String, dynamic>>> _loadImagesFSFloorTrap() async {
List<Map<String, dynamic>> files = [];
final ListResult result = await FirebaseStorage.instance
.ref(widget.value2)
.child('Female_Surau')
.child('Abulation_Area_Faucet')
.list();
final List allFiles = result.items;
await Future.forEach(allFiles, (file) async {
final String fileUrl = await file.getDownloadURL();
//final FullMetadata fileMeta = await file.getMetadata();
files.add({
'url': fileUrl,
'path': file.fullPath,
//'Facility': fileMeta.customMetadata?['Facility'] ?? 'Nobody',
});
});
return files;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Generate Report'),
centerTitle: true,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => const ProjectScreen()));
}),
),
backgroundColor: Theme.of(context).secondaryHeaderColor,
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 20.0, horizontal: 10.0),
child: Column(children: [
Column(children: [
Row(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.center,
children: const [
Padding(
padding: EdgeInsets.fromLTRB(
150, 10, 10, 10),
child: Text('Images:',
style: TextStyle(
fontSize: 18.0,
fontWeight:
FontWeight.bold,
)),
),
SizedBox(height: 20)
]),
Row(
children: [
Flexible(
child: FutureBuilder(
future:
_loadImagesFSFloorTrap(),
builder: (context,
AsyncSnapshot<
List<
Map<String,
dynamic>>>
snapshot) {
if (snapshot
.connectionState ==
ConnectionState.done) {
return ListView.builder(
itemExtent: 320,
scrollDirection:
Axis.vertical,
shrinkWrap: true,
itemCount: snapshot
.data?.length ??
0,
itemBuilder:
(context, index) {
//final Map
image = snapshot
.data![index];
return Column(
children: [
Image.network(
image?['url'],
width: 300,
height: 250,
fit: BoxFit
.cover,
),
const SizedBox(
height: 5),
//Text (
//image?['Facility']
//),
],
);
},
);
}
return const Center(
child:
CircularProgressIndicator(),
);
},
),
),
],
)
]),
]),
],
);
}),
)
]),
Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(130.0, 10.0, 0.0, 0.0),
child: Row(
children: [
ElevatedButton(
onPressed: (selectedFacility != null &&
selectedFacilityItems != null &&
selectedProject != null &&
selectedProjectItems != null &&
selectedName != null)
? () {
generatePdf();
}
: null,
child: const Text('Generate Report'),
style: ElevatedButton.styleFrom(
elevation: 5,
shape: const StadiumBorder(),
padding: const EdgeInsets.all(10),
minimumSize: const Size(150, 40),
),
),
],
),
),
],
)
]))));
}
//**************PDF**********************
Future<void> generatePdf() async {
//Create a new PDF document
PdfDocument document = PdfDocument();
//Set the page size
document.pageSettings.size = PdfPageSize.a4;
//Change the page orientation to landscape
document.pageSettings.orientation = PdfPageOrientation.landscape;
//Set the compression level
document.compressionLevel = PdfCompressionLevel.best;
//Set margin for all the pages
document.pageSettings.margins.all = 40;
//Create a string format to set text alignment
final PdfStringFormat format = PdfStringFormat(
alignment: PdfTextAlignment.center,
lineAlignment: PdfVerticalAlignment.middle);
final PdfStringFormat middleFormat =
PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle);
//Create padding, borders for PDF grid
final PdfPaddings paddingLogo =
PdfPaddings(left: 5, right: 5, top: 5, bottom: 5);
final PdfPaddings padding = PdfPaddings(left: 5);
//final PdfPen linePen = PdfPen(PdfColor(0, 0, 0), width: 2);
//final PdfPen lastRowBorderPen = PdfPen(PdfColor(0, 0, 0), width: 1);
//final PdfBorders borders = PdfBorders(
//left: linePen, top: linePen, bottom: linePen, right: linePen);
//final PdfBorders lastRowBorder = PdfBorders(
//left: linePen,
//top: linePen,
//bottom: lastRowBorderPen,
//right: linePen);
//Create a new font
final PdfFont fontHeader = PdfStandardFont(PdfFontFamily.timesRoman, 18);
final PdfFont fontSubHeader = PdfStandardFont(PdfFontFamily.timesRoman, 12);
final PdfFont fontContent = PdfStandardFont(PdfFontFamily.timesRoman, 12);
Future getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
File f = await getImageFileFromAssets('mrtlogo2.png');
// document.pages
//.add()
// .graphics
// .drawImage(
// PdfBitmap(f.readAsBytesSync()), const Rect.fromLTWH(0, 0, 0, 0)
// );
//Create a PdfGrid class
PdfGrid headerGrid = PdfGrid();
//Add the columns to the grid
headerGrid.columns.add(count: 8);
//Set column width
headerGrid.columns[0].width = 95;
headerGrid.columns[1].width = 95;
headerGrid.columns[2].width = 95;
headerGrid.columns[3].width = 95;
headerGrid.columns[4].width = 95;
headerGrid.columns[5].width = 95;
headerGrid.columns[6].width = 95;
headerGrid.columns[7].width = 95;
//Add header to the grid
headerGrid.headers.add(1);
//Add the rows to the grid
final PdfImage image = PdfBitmap(f.readAsBytesSync());
const Rect.fromLTWH(0, 0, 0, 0);
PdfGridRow headerRow1 = headerGrid.rows.add();
headerRow1.height = 60;
headerRow1.cells[0].value = 'INSPECTION REPORT';
headerRow1.cells[0].style.stringFormat = format;
headerRow1.cells[0].style.font = fontHeader;
headerRow1.cells[7].style.backgroundImage = image;
headerRow1.cells[7].style.cellPadding = paddingLogo;
headerRow1.cells[0].columnSpan = 7;
PdfGridRow headerRow2 = headerGrid.rows.add();
headerRow2.height = 25;
headerRow2.cells[0].value = 'Project:';
headerRow2.cells[2].value = widget.value1;
headerRow2.cells[4].value = 'Station/MSPR/Route No.:';
headerRow2.cells[6].value = widget.value2;
headerRow2.style.font = fontSubHeader;
headerRow2.cells[0].style.cellPadding = padding;
headerRow2.cells[0].style.stringFormat = middleFormat;
headerRow2.cells[2].style.stringFormat = format;
headerRow2.cells[4].style.cellPadding = padding;
headerRow2.cells[4].style.stringFormat = middleFormat;
headerRow2.cells[6].style.stringFormat = format;
headerRow2.cells[0].columnSpan = 2;
headerRow2.cells[2].columnSpan = 2;
headerRow2.cells[4].columnSpan = 2;
headerRow2.cells[6].columnSpan = 2;
PdfGridRow headerRow3 = headerGrid.rows.add();
headerRow3.height = 25;
headerRow3.cells[0].value = 'Inspected by:';
headerRow3.cells[2].value = widget.value3;
headerRow3.cells[4].value = 'Report Date:';
headerRow3.cells[6].value =
'${dateTimeEsc.day}/${dateTimeEsc.month}/${dateTimeEsc.year}';
headerRow3.style.font = fontSubHeader;
headerRow3.cells[0].style.cellPadding = padding;
headerRow3.cells[0].style.stringFormat = middleFormat;
headerRow3.cells[2].style.stringFormat = format;
headerRow3.cells[4].style.cellPadding = padding;
headerRow3.cells[4].style.stringFormat = middleFormat;
headerRow3.cells[6].style.stringFormat = format;
headerRow3.cells[0].columnSpan = 2;
headerRow3.cells[2].columnSpan = 2;
headerRow3.cells[4].columnSpan = 2;
headerRow3.cells[6].columnSpan = 2;
PdfGridRow headerRow4 = headerGrid.rows.add();
headerRow4.height = 25;
headerRow4.cells[0].value = 'Reference No.:';
headerRow4.cells[2].value = '';
headerRow4.cells[4].value = '';
headerRow4.cells[6].value = '';
headerRow4.style.font = fontSubHeader;
headerRow4.cells[0].style.cellPadding = padding;
headerRow4.cells[0].style.stringFormat = middleFormat;
headerRow4.cells[2].style.stringFormat = format;
headerRow4.cells[4].style.cellPadding = padding;
headerRow4.cells[4].style.stringFormat = middleFormat;
headerRow4.cells[6].style.stringFormat = format;
headerRow4.cells[0].columnSpan = 2;
headerRow4.cells[2].columnSpan = 2;
headerRow4.cells[4].columnSpan = 2;
headerRow4.cells[6].columnSpan = 2;
//Set the grid style
//grid.style = PdfGridStyle(
//cellPadding: PdfPaddings(left: 5, right: 3, top: 5, bottom: 5),
//backgroundBrush: PdfBrushes.white,
//textBrush: PdfBrushes.black,
//font: PdfStandardFont(PdfFontFamily.timesRoman, 12));
//Draw the grid
//headerGrid.draw(
//page: document.pages.add(), bounds: const Rect.fromLTWH(0, 0, 0, 0));
final PdfLayoutResult result =
headerGrid.draw(page: document.pages.add(), bounds: const Rect.fromLTWH(1, 1, 0, 0))!;
//Create a new grid
PdfGrid contentGrid = PdfGrid();
contentGrid.style.font = fontContent;
contentGrid.columns.add(count: 3);
//Add grid header
contentGrid.headers.add(1);
contentGrid.columns[0].width = 40;
contentGrid.columns[1].width = 300;
contentGrid.columns[2].width = 420;
//Get header and set values
final PdfGridRow contentHeader = contentGrid.headers[0];
contentHeader.style.font = fontContent;
contentHeader.cells[0].value = 'No.';
contentHeader.cells[0].style.cellPadding = padding;
contentHeader.cells[0].style.stringFormat = format;
contentHeader.cells[1].value = 'Comments';
contentHeader.cells[1].style.cellPadding = padding;
contentHeader.cells[1].style.stringFormat = format;
contentHeader.cells[2].value = 'Picture';
contentHeader.cells[2].style.cellPadding = padding;
contentHeader.cells[2].style.stringFormat = format;
//Add a row
final PdfGridRow contentRow1 = contentGrid.rows.add();
//Set height
contentRow1.height = 200;
contentRow1.cells[0].value = '1';
contentRow1.cells[0].style.stringFormat = format;
contentRow1.cells[1].value = commentsFSFaucet;
contentRow1.cells[1].style.stringFormat = format;
contentRow1.cells[2].style.backgroundImage = _loadImagesFSFaucet() as PdfImage?;
//contentRow1.cells[2].value = commentsFSFaucet;
//contentRow1.cells[2].style.stringFormat = format;
//Draw content grid based on the bounds calculated in first grid
contentGrid.draw(
page: result.page,
bounds:
Rect.fromLTWH(1, result.bounds.top + result.bounds.height, 0, 0));
//Save and launch the document
final List<int> bytes = await document.save();
//Dispose the document.
document.dispose();
final Directory directory = await getApplicationDocumentsDirectory();
final String path = directory.path;
final File file = File('$path/output.pdf');
await file.writeAsBytes(bytes, flush: true);
//Open the fine.
OpenFile.open('$path/output.pdf');
}
} Hi Arminder,
PdfImage objects only receive the image data as a base64 string representation or int array. So, we could not directly use the map item on it. We suggest you download the firebase image and create a new PdfBitmap object using that downloaded data and then assign it to the PDF grid cell background image.
You can refer to the following firebase documentation to download the image from firebase.
https://firebase.google.com/docs/storage/flutter/download-files
You can refer to the following code to create PdfBitmap and assign it to the PdfGrid cell background image.
|
//Create a bitmap object. PdfBitmap image = PdfBitmap(data);
//Assign the image to the grid cell background. contentRow1.cells[2].style.backgroundImage = image; |
Refer to the following UG/KB documentation for further details.
https://help.syncfusion.com/flutter/pdf/working-with-images#inserting-image-to-pdf-using-a-web-url
https://www.syncfusion.com/kb/11965/how-to-convert-image-to-pdf-in-syncfusion-flutter-pdf-library
Regards,
Gowthamraj K
If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.