buildPdf method

Future<File> buildPdf(
  1. List<String> imagePaths
)

Implementation

Future<File> buildPdf(List<String> imagePaths) async {
  final pdf = pw.Document();
  for (var path in imagePaths) {
    try {
      if (path.startsWith('file://')) {
        path = Uri.parse(path).toFilePath();
      }
      final bytes = await File(path).readAsBytes();

      // Use JpegImage for better compression and memory handling if it's a JPEG
      final image = pw.MemoryImage(bytes);

      pdf.addPage(
        pw.Page(
          margin: const pw.EdgeInsets.all(0),
          pageFormat: PdfPageFormat.a4.copyWith(
            marginBottom: 0,
            marginLeft: 0,
            marginRight: 0,
            marginTop: 0,
          ),
          build: (pw.Context context) {
            return pw.FullPage(
              ignoreMargins: true,
              child: pw.Center(
                child: pw.Image(image, fit: pw.BoxFit.contain),
              ),
            );
          },
        ),
      );
    } catch (e) {
      debugPrint('PixelToPdfService: Error adding page to PDF from $path: $e');
    }
  }

  final dir = await getTemporaryDirectory();
  final file = File(
    '${dir.path}/scan_${DateTime.now().millisecondsSinceEpoch}.pdf',
  );

  try {
    final pdfBytes = await pdf.save();
    await file.writeAsBytes(pdfBytes);
  } catch (e) {
    debugPrint('PixelToPdfService: Error saving PDF: $e');
    rethrow;
  }

  return file;
}