-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathmain.dart
453 lines (435 loc) · 16.6 KB
/
main.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import 'package:flutter/material.dart';
import 'package:pdfrx/pdfrx.dart';
import 'package:url_launcher/url_launcher.dart';
import 'markers_view.dart';
import 'outline_view.dart';
import 'password_dialog.dart';
import 'search_view.dart';
import 'thumbnails_view.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Pdfrx example',
home: MainPage(),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final documentRef = ValueNotifier<PdfDocumentRef?>(null);
final controller = PdfViewerController();
final showLeftPane = ValueNotifier<bool>(false);
final outline = ValueNotifier<List<PdfOutlineNode>?>(null);
late final textSearcher = PdfTextSearcher(controller)..addListener(_update);
final _markers = <int, List<Marker>>{};
PdfTextRanges? _selectedText;
void _update() {
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
textSearcher.removeListener(_update);
textSearcher.dispose();
showLeftPane.dispose();
outline.dispose();
documentRef.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
showLeftPane.value = !showLeftPane.value;
},
),
title: const Text('Pdfrx example'),
actions: [
IconButton(
icon: const Icon(
Icons.circle,
color: Colors.red,
),
onPressed: () => _addCurrentSelectionToMarkers(Colors.red),
),
IconButton(
icon: const Icon(
Icons.circle,
color: Colors.green,
),
onPressed: () => _addCurrentSelectionToMarkers(Colors.green),
),
IconButton(
icon: const Icon(
Icons.circle,
color: Colors.orangeAccent,
),
onPressed: () => _addCurrentSelectionToMarkers(Colors.orangeAccent),
),
IconButton(
icon: const Icon(Icons.zoom_in),
onPressed: () => controller.zoomUp(),
),
IconButton(
icon: const Icon(Icons.zoom_out),
onPressed: () => controller.zoomDown(),
),
IconButton(
icon: const Icon(Icons.first_page),
onPressed: () => controller.goToPage(pageNumber: 1),
),
IconButton(
icon: const Icon(Icons.last_page),
onPressed: () =>
controller.goToPage(pageNumber: controller.pages.length),
),
],
),
body: Row(
children: [
AnimatedSize(
duration: const Duration(milliseconds: 300),
child: ValueListenableBuilder(
valueListenable: showLeftPane,
builder: (context, showLeftPane, child) => SizedBox(
width: showLeftPane ? 300 : 0,
child: child!,
),
child: Padding(
padding: const EdgeInsets.fromLTRB(1, 0, 4, 0),
child: DefaultTabController(
length: 4,
child: Column(
children: [
const TabBar(tabs: [
Tab(icon: Icon(Icons.search), text: 'Search'),
Tab(icon: Icon(Icons.menu_book), text: 'TOC'),
Tab(icon: Icon(Icons.image), text: 'Pages'),
Tab(icon: Icon(Icons.bookmark), text: 'Markers'),
]),
Expanded(
child: TabBarView(
children: [
// NOTE: documentRef is not explicitly used but it indicates that
// the document is changed.
ValueListenableBuilder(
valueListenable: documentRef,
builder: (context, documentRef, child) =>
TextSearchView(
textSearcher: textSearcher,
),
),
ValueListenableBuilder(
valueListenable: outline,
builder: (context, outline, child) => OutlineView(
outline: outline,
controller: controller,
),
),
ValueListenableBuilder(
valueListenable: documentRef,
builder: (context, documentRef, child) =>
ThumbnailsView(
documentRef: documentRef,
controller: controller,
),
),
MarkersView(
markers:
_markers.values.expand((e) => e).toList(),
onTap: (marker) {
final rect =
controller.calcRectForRectInsidePage(
pageNumber: marker.ranges.pageText.pageNumber,
rect: marker.ranges.bounds,
);
controller.ensureVisible(rect);
},
onDeleteTap: (marker) {
_markers[marker.ranges.pageNumber]!
.remove(marker);
setState(() {});
},
),
],
),
),
],
),
),
),
),
),
Expanded(
child: Stack(
children: [
PdfViewer.asset(
'assets/hello.pdf',
// PdfViewer.file(
// r"D:\pdfrx\example\assets\hello.pdf",
// PdfViewer.uri(
// Uri.parse(
// 'https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf'),
// PdfViewer.uri(
// Uri.parse(kIsWeb
// ? 'assets/assets/hello.pdf'
// : 'https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf'),
// Set password provider to show password dialog
passwordProvider: () => passwordDialog(context),
controller: controller,
params: PdfViewerParams(
enableTextSelection: true,
maxScale: 8,
// facing pages algorithm
// layoutPages: (pages, params) {
// // They should be moved outside function
// const isRightToLeftReadingOrder = false;
// const needCoverPage = true;
// final width = pages.fold(
// 0.0, (prev, page) => max(prev, page.width));
// final pageLayouts = <Rect>[];
// double y = params.margin;
// for (int i = 0; i < pages.length; i++) {
// const offset = needCoverPage ? 1 : 0;
// final page = pages[i];
// final pos = i + offset;
// final isLeft = isRightToLeftReadingOrder
// ? (pos & 1) == 1
// : (pos & 1) == 0;
// final otherSide = (pos ^ 1) - offset;
// final h = 0 <= otherSide && otherSide < pages.length
// ? max(page.height, pages[otherSide].height)
// : page.height;
// pageLayouts.add(
// Rect.fromLTWH(
// isLeft
// ? width + params.margin - page.width
// : params.margin * 2 + width,
// y + (h - page.height) / 2,
// page.width,
// page.height,
// ),
// );
// if (pos & 1 == 1 || i + 1 == pages.length) {
// y += h + params.margin;
// }
// }
// return PdfPageLayout(
// pageLayouts: pageLayouts,
// documentSize: Size(
// (params.margin + width) * 2 + params.margin,
// y,
// ),
// );
// },
//
onViewSizeChanged: (viewSize, oldViewSize, controller) {
if (oldViewSize != null) {
//
// Calculate the matrix to keep the center position during device
// screen rotation
//
// The most important thing here is that the transformation matrix
// is not changed on the view change.
final centerPosition =
controller.value.calcPosition(oldViewSize);
final newMatrix =
controller.calcMatrixFor(centerPosition);
// Don't change the matrix in sync; the callback might be called
// during widget-tree's build process.
Future.delayed(
const Duration(milliseconds: 200),
() => controller.goTo(newMatrix),
);
}
},
// Scroll-thumbs example
//
viewerOverlayBuilder: (context, size) => [
//
// Double-tap to zoom
//
GestureDetector(
behavior: HitTestBehavior.translucent,
onDoubleTap: () {
controller.zoomUp(loop: true);
},
child: IgnorePointer(
child:
SizedBox(width: size.width, height: size.height),
),
),
//
// Scroll-thumbs example
//
// Show vertical scroll thumb on the right; it has page number on it
PdfViewerScrollThumb(
controller: controller,
orientation: ScrollbarOrientation.right,
thumbSize: const Size(40, 25),
thumbBuilder:
(context, thumbSize, pageNumber, controller) =>
Container(
color: Colors.black,
child: Center(
child: Text(
pageNumber.toString(),
style: const TextStyle(color: Colors.white),
),
),
),
),
// Just a simple horizontal scroll thumb on the bottom
PdfViewerScrollThumb(
controller: controller,
orientation: ScrollbarOrientation.bottom,
thumbSize: const Size(80, 30),
thumbBuilder:
(context, thumbSize, pageNumber, controller) =>
Container(
color: Colors.red,
),
),
],
//
// Loading progress indicator example
//
loadingBannerBuilder:
(context, bytesDownloaded, totalBytes) => Center(
child: CircularProgressIndicator(
value: totalBytes != null
? bytesDownloaded / totalBytes
: null,
backgroundColor: Colors.grey,
),
),
//
// Link handling example
//
linkHandlerParams: PdfLinkHandlerParams(
onLinkTap: (link) {
if (link.url != null) {
navigateToUrl(link.url!);
} else if (link.dest != null) {
controller.goToDest(link.dest);
}
},
),
pagePaintCallbacks: [
textSearcher.pageTextMatchPaintCallback,
_paintMarkers,
],
onDocumentChanged: (document) async {
if (document == null) {
documentRef.value = null;
outline.value = null;
_selectedText = null;
_markers.clear();
}
},
onViewerReady: (document, controller) async {
documentRef.value = controller.documentRef;
outline.value = await document.loadOutline();
},
onTextSelectionChange: (selection) {
_selectedText = selection;
},
),
),
],
),
),
],
),
);
}
void _paintMarkers(Canvas canvas, Rect pageRect, PdfPage page) {
final markers = _markers[page.pageNumber];
if (markers == null) {
return;
}
for (final marker in markers) {
final paint = Paint()
..color = marker.color.withAlpha(100)
..style = PaintingStyle.fill;
for (final range in marker.ranges.ranges) {
final f = PdfTextRangeWithFragments.fromTextRange(
marker.ranges.pageText,
range.start,
range.end,
);
if (f != null) {
canvas.drawRect(
f.bounds.toRectInPageRect(page: page, pageRect: pageRect),
paint,
);
}
}
}
}
void _addCurrentSelectionToMarkers(Color color) {
if (controller.isReady &&
_selectedText != null &&
_selectedText!.isNotEmpty) {
_markers
.putIfAbsent(_selectedText!.pageNumber, () => [])
.add(Marker(color, _selectedText!));
setState(() {});
}
}
Future<void> navigateToUrl(Uri url) async {
if (await shouldOpenUrl(context, url)) {
await launchUrl(url);
}
}
Future<bool> shouldOpenUrl(BuildContext context, Uri url) async {
final result = await showDialog<bool?>(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: const Text('Navigate to URL?'),
content: SelectionArea(
child: Text.rich(
TextSpan(
children: [
const TextSpan(
text:
'Do you want to navigate to the following location?\n'),
TextSpan(
text: url.toString(),
style: const TextStyle(color: Colors.blue),
),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Go'),
),
],
);
},
);
return result ?? false;
}
}