Matthias Nott
4 days ago a526ea4ce4a6da31222f73ca12c8dd9017fb2410
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdfrx/pdfrx.dart';
import 'package:share_plus/share_plus.dart';
/// Full-screen PDF viewer with pinch-to-zoom, page navigation, and share/save.
class PdfViewerScreen extends StatelessWidget {
  final Uint8List pdfBytes;
  final String title;
  const PdfViewerScreen({
    super.key,
    required this.pdfBytes,
    this.title = 'PDF',
  });
  Future<void> _share(BuildContext context) async {
    try {
      final dir = await getTemporaryDirectory();
      final safeName = title.replaceAll(RegExp(r'[^\w\s.-]'), '').trim();
      final fileName = safeName.endsWith('.pdf') ? safeName : '$safeName.pdf';
      final file = File('${dir.path}/$fileName');
      await file.writeAsBytes(pdfBytes);
      await SharePlus.instance.share(
        ShareParams(files: [XFile(file.path, mimeType: 'application/pdf')]),
      );
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Share failed: $e')),
        );
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title, style: const TextStyle(fontSize: 16)),
        backgroundColor: Colors.black87,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.ios_share),
            tooltip: 'Share / Save',
            onPressed: () => _share(context),
          ),
        ],
      ),
      backgroundColor: Colors.grey[900],
      body: PdfViewer.data(pdfBytes, sourceName: title),
    );
  }
}