import 'dart:io'; import 'dart:math' as math; import 'dart:ui'; import 'package:file_picker/file_picker.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:syncfusion_flutter_pdf/pdf.dart'; import '../models/ink_stroke.dart'; /// Service for PDF operations: file picking, info extraction, and annotation export. class PdfService { /// Pick a PDF file path using the cross-platform file_picker. Future pickPdfFile() async { final result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['pdf'], ); final files = result?.files; if (files == null || files.isEmpty) return null; return files.first.path; } /// Get the page count of the PDF at [filePath]. Future getPageCount(String filePath) async { final bytes = await File(filePath).readAsBytes(); final document = PdfDocument(inputBytes: bytes); try { return document.pages.count; } finally { document.dispose(); } } /// Get basic info about a PDF file: fileName and fileSize. Future> getPdfInfo(String filePath) async { final file = File(filePath); final fileSize = await file.length(); return {'fileName': p.basename(filePath), 'fileSize': fileSize}; } /// Export an annotated PDF by drawing ink strokes onto each page. /// /// [annotations] maps page index (0-based) to lists of [InkStroke]. /// Stroke coordinates are normalized to [0, 1] relative to the annotation /// overlay size used during capture, and are scaled to actual PDF page /// dimensions during export. /// /// Returns the path to the exported annotated PDF. Future exportAnnotatedPdf( String filePath, Map> annotations, ) async { final bytes = await File(filePath).readAsBytes(); final document = PdfDocument(inputBytes: bytes); try { for (final entry in annotations.entries) { final pageIndex = entry.key; final strokes = entry.value; if (strokes.isEmpty) continue; if (pageIndex >= document.pages.count) continue; final page = document.pages[pageIndex]; _renderStrokes(page, strokes); } final outputDir = await getTemporaryDirectory(); final baseName = p.basenameWithoutExtension(filePath); final outputPath = p.join(outputDir.path, '${baseName}_annotated.pdf'); final savedBytes = await document.save(); await File(outputPath).writeAsBytes(savedBytes, flush: true); return outputPath; } finally { document.dispose(); } } /// Delete a page at [pageIndex]. Returns true on success. Future deletePage(String filePath, int pageIndex) async { try { final bytes = await File(filePath).readAsBytes(); final document = PdfDocument(inputBytes: bytes); try { if (pageIndex < 0 || pageIndex >= document.pages.count) { return false; } document.pages.removeAt(pageIndex); final outputBytes = await document.save(); await File(filePath).writeAsBytes(outputBytes, flush: true); return true; } finally { document.dispose(); } } catch (_) { return false; } } /// Insert a blank A4 page (595 x 842 pt) after [afterIndex]. /// Returns true on success. Future insertBlankPage(String filePath, int afterIndex) async { try { final bytes = await File(filePath).readAsBytes(); final document = PdfDocument(inputBytes: bytes); final insertAt = (afterIndex + 1).clamp(0, document.pages.count); document.pages.insert(insertAt); final outputBytes = await document.save(); document.dispose(); await File(filePath).writeAsBytes(outputBytes, flush: true); return true; } catch (_) { return false; } } /// Rotate page at [pageIndex] 90 degrees clockwise. /// Returns true on success. Future rotatePage(String filePath, int pageIndex) async { try { final bytes = await File(filePath).readAsBytes(); final document = PdfDocument(inputBytes: bytes); try { if (pageIndex < 0 || pageIndex >= document.pages.count) { return false; } final page = document.pages[pageIndex]; final current = page.rotation; // Cycle through: 0 -> 90 -> 180 -> 270 -> 0 switch (current) { case PdfPageRotateAngle.rotateAngle0: page.rotation = PdfPageRotateAngle.rotateAngle90; case PdfPageRotateAngle.rotateAngle90: page.rotation = PdfPageRotateAngle.rotateAngle180; case PdfPageRotateAngle.rotateAngle180: page.rotation = PdfPageRotateAngle.rotateAngle270; case PdfPageRotateAngle.rotateAngle270: page.rotation = PdfPageRotateAngle.rotateAngle0; } final outputBytes = await document.save(); await File(filePath).writeAsBytes(outputBytes, flush: true); return true; } finally { document.dispose(); } } catch (_) { return false; } } /// Draw an image from [imagePath] onto the page at [pageIndex], /// fitted to the page dimensions while preserving aspect ratio. /// Returns the [pdfPath] on success, null on failure. Future insertImageOnPage( String pdfPath, int pageIndex, String imagePath, ) async { try { final pdfBytes = await File(pdfPath).readAsBytes(); final document = PdfDocument(inputBytes: pdfBytes); try { if (pageIndex < 0 || pageIndex >= document.pages.count) { return null; } final page = document.pages[pageIndex]; final imageBytes = await File(imagePath).readAsBytes(); final pdfImage = PdfBitmap(imageBytes); final pageSize = page.getClientSize(); // Fit the image to the page while preserving its aspect ratio // (letterboxed and centered), rather than stretching it to fill. final imageWidth = pdfImage.width.toDouble(); final imageHeight = pdfImage.height.toDouble(); final scale = (imageWidth <= 0 || imageHeight <= 0) ? 1.0 : math.min( pageSize.width / imageWidth, pageSize.height / imageHeight, ); final drawWidth = imageWidth * scale; final drawHeight = imageHeight * scale; final left = (pageSize.width - drawWidth) / 2; final top = (pageSize.height - drawHeight) / 2; page.graphics.drawImage( pdfImage, Rect.fromLTWH(left, top, drawWidth, drawHeight), ); final outputBytes = await document.save(); await File(pdfPath).writeAsBytes(outputBytes, flush: true); return pdfPath; } finally { document.dispose(); } } catch (_) { return null; } } /// Renders [strokes] onto a PDF [page] using normalized [0, 1] coordinates /// scaled to the actual page dimensions. void _renderStrokes(PdfPage page, List strokes) { final graphics = page.graphics; final pageSize = page.getClientSize(); for (final stroke in strokes) { if (stroke.points.isEmpty) continue; final color = stroke.color; final r = (color >> 16) & 0xFF; final g = (color >> 8) & 0xFF; final b = color & 0xFF; final a = (color >> 24) & 0xFF; final pen = PdfPen(PdfColor(r, g, b, a)); pen.width = stroke.strokeWidth.clamp(1.0, 8.0); if (stroke.points.length == 1) { // Single point — draw a dot final pt = stroke.points.first; graphics.drawEllipse( Rect.fromCenter( center: Offset(pt.x * pageSize.width, pt.y * pageSize.height), width: stroke.strokeWidth, height: stroke.strokeWidth, ), pen: pen, ); } else { // Draw line segments between consecutive points for (int i = 0; i < stroke.points.length - 1; i++) { final p1 = stroke.points[i]; final p2 = stroke.points[i + 1]; graphics.drawLine( pen, Offset(p1.x * pageSize.width, p1.y * pageSize.height), Offset(p2.x * pageSize.width, p2.y * pageSize.height), ); } } } } }