savePdfDocToFile function
Implementation
Future<List<int>> savePdfDocToFile(PdfDocument pdfDoc, File file) async {
try {
// Get the document bytes
final List<int> bytes = await pdfDoc.save();
// Write in chunks to avoid memory spike
final IOSink sink = file.openWrite();
const int chunkSize = 64 * 1024; // 64KB chunks
for (int i = 0; i < bytes.length; i += chunkSize) {
final int end =
(i + chunkSize < bytes.length) ? i + chunkSize : bytes.length;
sink.add(bytes.sublist(i, end));
await sink.flush();
// Yield control periodically to prevent blocking
if (i % (chunkSize * 5) == 0) {
await Future.delayed(Duration.zero);
}
}
await sink.close();
return bytes;
} catch (e) {
return [];
}
}