-
Notifications
You must be signed in to change notification settings - Fork 6
/
pdf_thumbnail.dart
263 lines (237 loc) · 7.49 KB
/
pdf_thumbnail.dart
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright (c) 2022, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pdfx/pdfx.dart';
/// Callback when the user taps on a thumbnail
typedef ThumbnailPageCallback = void Function(int page);
/// Function that returns page number widget
typedef CurrentPageWidget = Widget Function(int page, bool isCurrentPage);
/// {@template pdf_thumbnail}
/// Thumbnail viewer for pdfs
/// {@endtemplate}
class PdfThumbnail extends StatefulWidget {
//@TODO
// factory PdfThumbnail.fromAsset(String asset) {
// return PdfThumbnail._();
// }
/// Creates a [PdfThumbnail] from a file.
factory PdfThumbnail.fromFile(
String path, {
Key? key,
Color? backgroundColor,
BoxDecoration? currentPageDecoration,
CurrentPageWidget? currentPageWidget,
double? height,
ThumbnailPageCallback? onPageClicked,
required int currentPage,
Widget? loadingIndicator,
ImageThumbnailCacher? cacher,
bool? scrollToCurrentPage,
Widget? closeButton,
}) {
return PdfThumbnail._(
key: key,
path: path,
backgroundColor: backgroundColor ?? Colors.black,
height: height ?? 200,
onPageClicked: onPageClicked,
currentPage: currentPage,
currentPageWidget:
currentPageWidget ?? (page, isCurrent) => const SizedBox(),
currentPageDecoration: currentPageDecoration ??
BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.blue,
width: 4,
),
),
loadingIndicator: loadingIndicator ??
const Center(
child: CircularProgressIndicator(),
),
cacher: cacher,
scrollToCurrentPage: scrollToCurrentPage ?? false,
closeButton: closeButton,
);
}
const PdfThumbnail._({
super.key,
this.path,
this.backgroundColor,
required this.height,
this.onPageClicked,
required this.currentPage,
this.currentPageDecoration,
this.loadingIndicator,
this.currentPageWidget,
this.cacher,
this.scrollToCurrentPage = false,
this.closeButton,
});
/// File path
final String? path;
/// Background color
final Color? backgroundColor;
/// Decoration for current page
final BoxDecoration? currentPageDecoration;
/// Simple function that returns widget that shows the page number.
/// Widget will be in [Stack] so you can use [Positioned] or [Align]
final CurrentPageWidget? currentPageWidget;
/// Height
final double height;
/// Callback to run when a page is clicked
final ThumbnailPageCallback? onPageClicked;
/// Current page, index + 1
final int currentPage;
/// Loading indicator
final Widget? loadingIndicator;
/// Close button
final Widget? closeButton;
/// Interface to manage caching
final ImageThumbnailCacher? cacher;
/// Whether page browser will scroll to the current page or not,
/// false by default
final bool scrollToCurrentPage;
@override
State<PdfThumbnail> createState() => _PdfThumbnailState();
}
class _PdfThumbnailState extends State<PdfThumbnail> {
late ScrollController controller;
@override
void initState() {
controller = ScrollController();
imagesFuture = _render(widget.path!, widget.cacher)
..then((value) async {
if (widget.scrollToCurrentPage) {
WidgetsBinding.instance.addPostFrameCallback((timestamp) {
swipeToPage(widget.currentPage, value.length);
});
}
});
super.initState();
}
late Future<Map<int, Uint8List>> imagesFuture;
@override
Widget build(BuildContext context) {
return Column(
children: [
if (widget.closeButton != null) widget.closeButton!,
Container(
height: widget.height,
color: widget.backgroundColor,
child: FutureBuilder<Map<int, Uint8List>>(
future: imagesFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
final images = snapshot.data!;
return ListView.builder(
controller: controller,
padding: EdgeInsets.symmetric(vertical: widget.height * 0.1),
scrollDirection: Axis.horizontal,
itemCount: images.length,
itemBuilder: (context, index) {
final pageNumber = index + 1;
final isCurrentPage = pageNumber == widget.currentPage;
final image = images[pageNumber];
if (image == null) {
return const SizedBox();
}
return GestureDetector(
onTap: () => widget.onPageClicked?.call(index),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Stack(
children: [
DecoratedBox(
key: Key('thumbnail_$pageNumber'),
decoration: isCurrentPage
? widget.currentPageDecoration!
: const BoxDecoration(
color: Colors.white,
),
child: Image.memory(image),
),
widget.currentPageWidget!(
pageNumber, isCurrentPage),
],
),
),
);
},
);
} else {
return widget.loadingIndicator!;
}
},
),
),
],
);
}
void swipeToPage(int page, int itemCount) {
final contentSize = controller.position.viewportDimension +
controller.position.maxScrollExtent;
final index = page - 1;
final target = contentSize * index / itemCount;
controller.animateTo(
target,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
Future<Map<int, Uint8List>> _render(
String filePath,
ImageThumbnailCacher? cacher,
) async {
final images = <int, Uint8List>{};
try {
if (cacher != null) {
final cached = await cacher.read(filePath);
if (cached != null && cached.isNotEmpty) {
return cached;
}
}
final document = await PdfDocument.openFile(filePath);
for (var pageNumber = 1; pageNumber <= document.pagesCount; pageNumber++) {
final page = await document.getPage(pageNumber);
final pageImage = await page.render(
width: page.width,
height: page.height,
);
images[pageNumber] = pageImage!.bytes;
await page.close();
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
if (cacher != null) {
await cacher.write(id: filePath, map: images);
}
return images;
}
/// Interface for caching thumbnails
abstract class ImageThumbnailCacher {
/// Read from cache
Future<PageToImage?> read(String id);
/// Write to cache
Future<bool> write({
required String id,
required PageToImage map,
});
}
/// Page to image map
typedef PageToImage = Map<int, Uint8List>;