import 'dart:typed_data'; import 'package:sysfarma_mobile/src/core/network/api_client.dart'; import 'package:flutter/material.dart'; import 'package:printing/printing.dart'; import 'package:url_launcher/url_launcher.dart'; class PdfHelper { /// Open an unauthenticated PDF in the system browser. static Future openPdf(String url) async { // ignore: avoid_print print('[EnterFarma] PdfHelper.openPdf url=$url'); final uri = Uri.tryParse(url); if (uri == null) return false; try { return await launchUrl(uri, mode: LaunchMode.externalApplication); } catch (e) { // ignore: avoid_print print('[EnterFarma] PdfHelper.openPdf EXCEPTION: $e'); return false; } } /// Download an authenticated PDF (sending the session token) and show it /// using the native printing viewer (which supports share + print). static Future openAuthenticatedPdf({ required BuildContext context, required ApiClient apiClient, required String url, required String title, }) async { // ignore: avoid_print print('[EnterFarma] openAuthenticatedPdf url=$url'); final messenger = ScaffoldMessenger.maybeOf(context); messenger?.showSnackBar( SnackBar(content: Text('Descargando $title...'), duration: const Duration(seconds: 2)), ); final bytes = await apiClient.downloadAuthenticatedFile(url); if (bytes == null || bytes.isEmpty) { messenger?.showSnackBar( SnackBar( content: Text('No se pudo descargar $title'), backgroundColor: Colors.red, ), ); return false; } final data = Uint8List.fromList(bytes); try { await Printing.layoutPdf( name: title, onLayout: (format) async => data, ); return true; } catch (e) { // ignore: avoid_print print('[EnterFarma] openAuthenticatedPdf Printing EXCEPTION: $e'); // Fallback: open share sheet with the bytes try { await Printing.sharePdf(bytes: data, filename: '$title.pdf'); return true; } catch (e2) { // ignore: avoid_print print('[EnterFarma] openAuthenticatedPdf sharePdf EXCEPTION: $e2'); messenger?.showSnackBar( SnackBar( content: Text('No se pudo abrir el PDF: $e'), backgroundColor: Colors.red, ), ); return false; } } } }