/
BookPdf.cs
826 lines (748 loc) · 25.3 KB
/
BookPdf.cs
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows;
using Windows.Storage;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using pdf = Windows.Data.Pdf;
using System.IO;
using System.Collections;
using BookViewerApp.Helper;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Collections.Immutable;
using System.Threading;
using static System.Net.Mime.MediaTypeNames;
#nullable enable
namespace BookViewerApp.Books
{
public class PdfBook : IBookFixed, IDirectionProvider, ITocProvider, IPasswordPdovider, IDisposable
{
public pdf.PdfDocument? Content { get; private set; }
private bool PageLoaded = false;
public string? Password { get; private set; } = null;
public event EventHandler? Loaded;
public uint PageCount => PageLoaded ? Content?.PageCount ?? 0 : 0;
public string? ID
{
get; private set;
}
public Direction Direction { get; private set; } = Direction.Default;
public TocItem[] Toc { get; private set; } = new TocItem[0];
public bool PasswordRemember { get; private set; }
public IPageFixed? GetPage(uint i)
{
if (Content is null) return null;
if (i < PageCount) return new PdfPage(Content.GetPage(i), string.Join(", ", GetNameFromToc((int)i)));
else throw new Exception("Incorrect page.");
}
void PrepareNameFromTocCache()
{
Dictionary<int, List<string>> result = new();
void AddItem(int page, string name)
{
List<string> list;
if (result.TryGetValue(page, out var value)) list = value; else result[page] = list = new List<string>();
list.Add(name);
}
AddItemsFromToc(Toc);
void AddItemsFromToc(IEnumerable<TocItem> tocs)
{
foreach (var item in tocs)
{
AddItem(item.Page, item.Title);
if (item.Children is not null and { Length: > 0 }) AddItemsFromToc(item.Children);
}
}
this.ReverseDictionary = result.ToDictionary(a => a.Key, a => a.Value.ToArray());
}
public IEnumerable<string> GetNameFromToc(int page)
{
if (ReverseDictionary.TryGetValue(page, out var r)) return r; else return Array.Empty<string>();
}
Dictionary<int, string[]> ReverseDictionary = new();
public static iTextSharp.text.pdf.PdfReader? GetPdfReader(Stream stream, string? password)
{
try
{
if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin);
if (password is null)
{
return new iTextSharp.text.pdf.PdfReader(stream, false);
//return new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(stream), null);
}
else
{
//Encoding of password depends on the implementation if it's not ISO 32000-2.
//https://stackoverflow.com/questions/57328735/use-itext-7-to-open-a-password-protected-pdf-file-with-non-ascii-characters
//It's not correct... but UTF8 should be fine for many cases.
return new iTextSharp.text.pdf.PdfReader(stream, Encoding.UTF8.GetBytes(password), false);
//Following throws NullReferenceException. PDF file has some problem? I don't think so.
//https://stackoverflow.com/questions/5121169/cant-read-some-pdf-files-with-itextsharp
//return new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(stream), Encoding.UTF8.GetBytes(password));
}
}
catch (iTextSharp.text.pdf.BadPasswordException)
{
return null;
}
catch
{
return null;
}
}
//public static iTextSharp.text.pdf.PdfReader? GetPdfReader(iTextSharp.text.pdf.RandomAccessFileOrArray raf, string? password)
//{
// try
// {
// raf.Seek(0);
// if (password is null)
// {
// return new iTextSharp.text.pdf.PdfReader(raf, null);
// }
// else
// {
// return new iTextSharp.text.pdf.PdfReader(raf, Encoding.UTF8.GetBytes(password));
// }
// }
// catch (iTextSharp.text.pdf.BadPasswordException)
// {
// return null;
// }
// catch
// {
// return null;
// }
//}
//Note:
//Type has changed due to the change in the library. To see old version:
//https://github.com/kurema/BookViewerApp3/blob/7b5e4149c0bd5dcc2117ba8deab41d29d8ffaa1b/BookViewerApp/Books/BookPdf.cs
public static TocItem[] GetTocs(Array? list, System.util.INullValueDictionary<object, iTextSharp.text.pdf.PdfObject> nd, List<iTextSharp.text.pdf.PrIndirectReference> pageRefs)
{
int GetPage(iTextSharp.text.pdf.PdfIndirectReference pref)
{
return pageRefs.FindIndex(a =>
{
return a.Number == pref.Number && a.Generation == pref.Generation;
});
}
if (list is null) return new TocItem[0];
var result = new List<TocItem>();
foreach (var item in list)
{
TocItem tocItem = new();
var t = item.GetType();
if (item is System.util.NullValueDictionary<string, object> itemd)
{
if (itemd.ContainsKey("Named") && itemd["Named"] is string named)
{
if (nd.ContainsKey(named) && nd[named] is iTextSharp.text.pdf.PdfArray nditem)
{
//Note
//http://www.pdf-tools.trustss.co.jp/Syntax/catalog.html#destinations
if (nditem.Length > 0 && nditem[0] is iTextSharp.text.pdf.PdfIndirectReference pir)
{
//This pir thing is not page number. This is reference to the /Page.
//https://stackoverflow.com/questions/30855432/how-to-get-the-page-number-of-an-arbitrary-pdf-object
tocItem.Page = GetPage(pir);
}
}
else if (nd.ContainsKey(named) && nd[named] is iTextSharp.text.pdf.PdfDictionary ndDict)
{
//I dont have PDF file to test this...
continue;
}
}
else if (itemd.ContainsKey("Page"))
{
if (itemd["Page"] is string s)
{
var res = s.Split(' ');
if (res.Length > 0 && int.TryParse(res[0], out int page))
{
tocItem.Page = page - 1;
}
else
{
continue;
}
}
else if (itemd["Page"] is iTextSharp.text.pdf.PdfArray nditem)
{
//There may be the case where this is PdfIndirectReference... But I dont have one.
//Does this really happen?
if (nditem.Length > 0 && nditem[0] is iTextSharp.text.pdf.PdfIndirectReference pir)
{
tocItem.Page = GetPage(pir);
}
}
else if (itemd["Page"] is IEnumerable nditem2)
{
//I don't know, but iTextSharp.text.pdf.PdfArray seems to change in the future or already. This should work in many case.
foreach (var item2 in nditem2)
{
if (item2 is iTextSharp.text.pdf.PdfIndirectReference pir)
{
tocItem.Page = GetPage(pir);
break;
}
}
}
else
{
continue;
}
}
else { continue; }
if (itemd.ContainsKey("Title") && itemd["Title"] is string title)
{
tocItem.Title = title;
}
else { continue; }
if (itemd.ContainsKey("Kids"))
{
if (itemd["Kids"] is ArrayList kids)
{
//Old, should not be called.
tocItem.Children = GetTocs(kids.ToArray(), nd, pageRefs);
}
else if (itemd["Kids"] is List<System.util.INullValueDictionary<string, object>> kids2)
{
//Current
tocItem.Children = GetTocs(kids2.ToArray(), nd, pageRefs);
}
else if (itemd["Kids"] is List<object> kids3)
{
//General
tocItem.Children = GetTocs(kids3.ToArray(), nd, pageRefs);
}
}
result.Add(tocItem);
}
}
return result.ToArray();
}
public async Task Load(IStorageFile file, Func<int, Task<(string password, bool remember)>> passwordRequestedCallback, Func<string, Task> errorCallback, IEnumerable<string>? defaultPasswords = null, CancellationTokenSource? cancellationTokenSource = null, bool skipPasswordTrial = false)
{
using Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenReadAsync();
await Load(stream, file.Name, passwordRequestedCallback, errorCallback, defaultPasswords, cancellationTokenSource, skipPasswordTrial);
}
CancellationTokenSource? cancellation = null;
public async Task Load(Windows.Storage.Streams.IRandomAccessStream stream, string fileName, Func<int, Task<(string password, bool remember)>> passwordRequestedCallback, Func<string, Task> errorCallback, IEnumerable<string>? defaultPasswords = null, CancellationTokenSource? cancellationTokenSource = null, bool skipPasswordTrial = false)
{
string? password = null;
bool passSave = false;
//If you want users to require password just to open the file, set this false.
bool allowUserPassword = true;
iTextSharp.text.pdf.PdfReader.AllowOpenWithFullPermissions = allowUserPassword;
bool contentLoaded = false;
string? id = null;
iTextSharp.text.pdf.PdfReader? pr = null;
cancellation?.Cancel();
var cancel = cancellation = new CancellationTokenSource();
cancellationTokenSource?.Token.Register(() => { try { if (!cancel.IsCancellationRequested) cancel.Cancel(); } catch { } });
Task? cracker = null;
try
{
//var raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(streamClassic);
bool isPrOk() => pr is not null && pr != null && (allowUserPassword || pr.IsOpenedWithFullPermissions);
bool isReaderOk(iTextSharp.text.pdf.PdfReader? reader) => reader is not null && reader != null && (allowUserPassword || reader.IsOpenedWithFullPermissions);
using var streamClassic = stream.AsStream();
#region Password
pr = GetPdfReader(streamClassic, null);
//pr = GetPdfReader(raf, null);
if (isPrOk()) goto PasswordSuccess;
bool crackSuccess = false;
static IEnumerable<string> GetCapitalCombinations(string text)
{
yield return text;
yield return text.ToUpperInvariant();
yield return text.ToLowerInvariant();
if (text.Length >= 2) yield return $"{char.ToUpperInvariant(text[0])}{text.Substring(1).ToLowerInvariant()}";
}
#if true
{
try
{
if (defaultPasswords.Any())
{
var word = defaultPasswords.First();
streamClassic.Seek(0, SeekOrigin.Begin);
pr = new iTextSharp.text.pdf.PdfReader(streamClassic, Encoding.UTF8.GetBytes(word), false);
if (isPrOk())
{
crackSuccess = true;
password = word;
passSave = true;
goto PasswordSuccess;
}
}
}
catch (iTextSharp.text.pdf.BadPasswordExceptionTriable badPw)
{
if (badPw.CanTryPassword && !skipPasswordTrial)
{
cracker = Task.Run(async () =>
{
Parallel.ForEach(defaultPasswords.SelectMany(a => GetCapitalCombinations(a).Distinct()).Where(a => a != defaultPasswords.First()) ?? new string[0], new ParallelOptions()
{
CancellationToken = cancel.Token,
}, (candidate, state) =>
{
var priviousePriority = Thread.CurrentThread.Priority;
try
{
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
if (cancel.IsCancellationRequested) state.Break();
if (iTextSharp.text.pdf.BadPasswordExceptionTriable.IsSucess(badPw.TryPassword(Encoding.UTF8.GetBytes(candidate))))
{
try
{
using var streamClassic2 = stream.AsStream();
var pr2 = GetPdfReader(streamClassic2, candidate);
if (isReaderOk(pr2))
{
pr = pr2;
password = candidate;
crackSuccess = true;
state.Break();
}
}
catch
{
}
}
}
finally
{
Thread.CurrentThread.Priority = priviousePriority;
}
});
}, cancel.Token);
}
}
}
#else
{
try
{
if (defaultPasswords.Any())
{
var word = defaultPasswords.First();
streamClassic.Seek(0, SeekOrigin.Begin);
var p = new iTextSharp.text.pdf.PdfReaderTriable(streamClassic, Encoding.UTF8.GetBytes(word));
streamClassic.Seek(0, SeekOrigin.Begin);
crackSuccess = true;
pr = GetPdfReader(streamClassic, word);
password = word;
passSave = true;
goto PasswordSuccess;
}
}
catch (iTextSharp.text.pdf.BadPasswordExceptionTriable badPw)
{
if (badPw.CanTryPassword)
{
cracker = Task.Run(async () =>
{
Parallel.ForEach(defaultPasswords.Skip(1) ?? new string[0], new ParallelOptions()
{
CancellationToken = cancel.Token
}, (item2, state) =>
{
if(cancel.IsCancellationRequested) state.Break();
foreach (var item1 in GetCapitalCombinations(item2).Distinct())
{
//var item1 = item2;
if (iTextSharp.text.pdf.BadPasswordExceptionTriable.IsSucess(badPw.TryPassword(Encoding.UTF8.GetBytes(item1))))
{
try
{
using var streamClassic2 = stream.AsStream();
var pr2 = GetPdfReader(streamClassic2, item1);
if (isReaderOk(pr2))
{
pr = pr2;
password = item1;
crackSuccess = true;
state.Break();
}
}
catch (Exception e)
{
}
}
}
});
}, cancel.Token);
}
}
catch (Exception e)
{
if (!crackSuccess)
{
try
{
var word = defaultPasswords.First();
pr = GetPdfReader(streamClassic, word);
password = word;
passSave = true;
goto PasswordSuccess;
}
catch { crackSuccess = false; }
}
}
}
#endif
try
{
for (int i = 0; i < 10; i++)
{
var result = await passwordRequestedCallback(i);
passSave = result.remember;
if (crackSuccess && isPrOk()) { passSave = true; goto PasswordSuccess; }
try
{
streamClassic.Seek(0, SeekOrigin.Begin);
pr = new iTextSharp.text.pdf.PdfReader(streamClassic, Encoding.UTF8.GetBytes(result.password), false);
if (isPrOk()) { password = result.password; goto PasswordSuccess; }
}
catch (iTextSharp.text.pdf.BadPasswordExceptionTriable badPw)
{
//Try passwords with different cases.
if (badPw.CanTryPassword)
{
foreach (var item in GetCapitalCombinations(result.password).Distinct().Where(a => a != result.password))
{
if (iTextSharp.text.pdf.BadPasswordExceptionTriable.IsSucess(badPw.TryPassword(Encoding.UTF8.GetBytes(item))))
{
streamClassic.Seek(0, SeekOrigin.Begin);
pr = new iTextSharp.text.pdf.PdfReader(streamClassic, Encoding.UTF8.GetBytes(item), false);
if (isPrOk()) { password = item; goto PasswordSuccess; }
}
}
}
}
catch
{
//If there's a problem with PdfReader, we just try with PdfDocument.
//This code is unlikely to be executed because iTextSharp's support is better but just in case.
foreach (var pass in GetCapitalCombinations(result.password).Distinct().Where(a => a != result.password))
{
try
{
using var s2 = stream.CloneStream();
s2.Seek(0);
//We have to load id beforehand because stream is locked if pass is correct.
id ??= await LoadIdFromStream(s2);
s2.Seek(0);
Content = await pdf.PdfDocument.LoadFromStreamAsync(s2, pass);
contentLoaded = true;
password = pass;
//Continue without iText (pr).
pr = null;
goto PasswordSuccess;
}
catch
{
continue;
}
}
}
}
}
catch { if (crackSuccess) { passSave = true; } else { password = null; passSave = false; } }
if (cracker is not null && !cracker.IsCompleted) try
{
await cracker;
if (crackSuccess) { passSave = true; goto PasswordSuccess; }
}
catch { }
throw new iTextSharp.text.pdf.BadPasswordException("All passwords wrong");
#endregion
PasswordSuccess:;
if (pr is null || pr == null) throw new NullReferenceException(nameof(pr));
try
{
//Get page direction information.
//It took some hours to write next line. Thanks for
//http://itext.2136553.n4.nabble.com/Using-getSimpleViewerPreferences-td2167775.html
//私が書いた記事はこちら。
//https://qiita.com/kurema/items/3f274507aa5cf9e845a8
//Somehow NullReferenceException was thrown here. So `pr is null` seems to be not enough. It have to be `pr == null`.
var vp = iTextSharp.text.pdf.intern.PdfViewerPreferencesImp.GetViewerPreferences(pr.Catalog).GetViewerPreferences();
//L2R document often don't have Direction information.
//But it look like "L2R" in Acrobat Reader.
//Direction = Direction.Default
Direction = Direction.L2R;
if (vp.Contains(iTextSharp.text.pdf.PdfName.Direction))
{
var name = vp.GetAsName(iTextSharp.text.pdf.PdfName.Direction);
if (name == iTextSharp.text.pdf.PdfName.R2L)
{
Direction = Direction.R2L;
}
else if (name == iTextSharp.text.pdf.PdfName.L2R)
{
Direction = Direction.L2R;
}
}
}
catch { }
try
{
//https://github.com/VahidN/iTextSharp.LGPLv2.Core/blob/73605fa82fb00e9e8670991c9e410c684731f9f8/src/iTextSharp.LGPLv2.Core/iTextSharp/text/pdf/PdfReader.cs#L3366
//It seems to be...
//documentIDs[0] doesn't change when you edit.
//documentIDs[1] does. documentIDs[1] does not always exist.
var documentIDs = pr.Trailer.GetAsArray(iTextSharp.text.pdf.PdfName.Id);
if (documentIDs != null && documentIDs.Size > 0)
{
id = Functions.GetHash(documentIDs[0].GetBytes().AsBuffer());
}
}
catch
{
}
var bm = iTextSharp.text.pdf.SimpleBookmark.GetBookmark(pr)?.ToArray();
var nd = pr.GetNamedDestination(false);
//Pdf's page start from 1 somehow.
var pageRefs = new List<iTextSharp.text.pdf.PrIndirectReference>();
for (int i = 1; i <= pr.NumberOfPages; i++)
{
var oref = pr.GetPageOrigRef(i);
pageRefs.Add(oref);
}
Toc = GetTocs(bm, nd, pageRefs);
PrepareNameFromTocCache();
// Open even when iTextSharp fails.
}
catch { }
static async Task<string?> LoadIdFromStream(Windows.Storage.Streams.IRandomAccessStream stream)
{
try
{
//When PDF ID is unavailable, Hash(Hash([first 2048 bytes of the file])+"\nSize:"+file size) is used.
//Problems are
//・Some books may have the same first 2048 bytes.
//・You may edit PDF file with same file size.
//But it's much better than just fileName+pageCount.
uint length = 2048;
var buffer = new Windows.Storage.Streams.Buffer(length);
stream.Seek(0);
await stream.ReadAsync(buffer, length, Windows.Storage.Streams.InputStreamOptions.Partial);
stream.Seek(0);
return Functions.GetHash(Functions.GetHash(buffer) + "\nSize:" + stream.Size);
}
catch
{
return null;
}
}
id ??= await LoadIdFromStream(stream);
try
{
if (cancel.IsCancellationRequested) return;
async Task OpenPdfCommon(Func<Task<pdf.PdfDocument?>> contentProvider, string errorMessageKey)
{
try { Content = await contentProvider.Invoke(); }
catch
{
try
{
if (pr is null) throw;
//Use iTextSharp to remove password and store it in memory.
//This will eat lots of memory.
//I'm not sure if I need using here.
Windows.Storage.Streams.InMemoryRandomAccessStream ms = new();
using var stamper = new iTextSharp.text.pdf.PdfStamper(pr, ms.AsStream());
stamper.Close();
Content = await pdf.PdfDocument.LoadFromStreamAsync(ms);
}
catch (Exception e)
{
var task = errorCallback?.Invoke(string.Format(Managers.ResourceManager.Loader.GetString(errorMessageKey), e.Message, e.StackTrace));
if (task is not null) await task;
}
}
}
if (contentLoaded)
{
Password = password;
PasswordRemember = passSave;
}
else if (password is null)
{
//It's stupid but it seems we need owner password to LoadFromStreamAsync();
await OpenPdfCommon(async () => await pdf.PdfDocument.LoadFromStreamAsync(stream), "Book/Pdf/Error/Message/Normal");
}
else
{
Password = password;
PasswordRemember = passSave;
await OpenPdfCommon(async () => await pdf.PdfDocument.LoadFromStreamAsync(stream, password), "Book/Pdf/Error/Message/PasswordCorrect");
}
}
catch { }
finally
{
pr?.Close();
pr?.Dispose();
if (cancel?.IsCancellationRequested == false) cancel?.Cancel();
}
OnLoaded(new EventArgs());
PageLoaded = true;
ID = id ?? Functions.GetHash(Functions.CombineStringAndDouble(fileName, Content?.PageCount ?? 0));
}
private void OnLoaded(EventArgs e)
{
Loaded?.Invoke(this, e);
}
public IPageFixed? GetPageCover()
{
return GetPage(0);
}
public void Dispose()
{
try
{
if (Content is not null)
{
//https://stackoverflow.com/questions/48380522/how-to-release-dispose-windows-data-pdfdocument
//I don't think it's working.
System.Runtime.InteropServices.Marshal.ReleaseComObject(Content);
Content = null;
}
}
catch
{
}
try
{
if (cancellation?.IsCancellationRequested == false) cancellation?.Cancel();
}
catch
{
}
}
}
}
namespace BookViewerApp.Books
{
public class PdfPage : IPageFixed
{
public pdf.PdfPage Content { get; private set; }
//public IPageOptions? Option
//{
// get; set;
//}
//public IPageOptions? LastOption;
private pdf.PdfPageRenderOptions? LastPdfOption;
public string Path => string.Empty;
public PdfPage(pdf.PdfPage page, string? title = null)
{
Content = page;
Title = title ?? string.Empty;
}
public string Title { get; private set; }
protected double RenderScaleDefault => ((bool)Storages.SettingStorage.GetValue("PdfRenderScaling")) ? 2.0 : 1.0;
protected double RenderScaleMinimum => ((bool)Storages.SettingStorage.GetValue("PdfRenderScaling")) ? 1.3 : 0.95;
public async Task RenderToStreamAsync(Windows.Storage.Streams.IRandomAccessStream stream, double width, double height)
{
if (width == 0 || height == 0)
{
try
{
var bound = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds;
var scaleFactor = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
width = bound.Width * scaleFactor;
height = bound.Height * scaleFactor;
}
catch
{
await Content.RenderToStreamAsync(stream);
return;
}
}
var pdfOption = new pdf.PdfPageRenderOptions();
if (height / Content.Size.Height < width / Content.Size.Width)
{
pdfOption.DestinationHeight = (uint)(height * RenderScaleDefault);
}
else
{
pdfOption.DestinationWidth = (uint)(width * RenderScaleDefault);
}
LastPdfOption = pdfOption;
await Content.RenderToStreamAsync(stream, pdfOption);
//if (Option != null)
//{
// //Strange code. Maybe fix needed.
// if (Option is PageOptionsControl)
// {
// LastOption = (PageOptions)(PageOptionsControl)Option;
// }
// else { LastOption = Option; }
// var pdfOption = new pdf.PdfPageRenderOptions();
// if (Option.TargetHeight / Content.Size.Height < Option.TargetWidth / Content.Size.Width)
// {
// pdfOption.DestinationHeight = (uint)Option.TargetHeight * 2;
// }
// else
// {
// pdfOption.DestinationWidth = (uint)Option.TargetWidth * 2;
// }
// await Content.RenderToStreamAsync(stream, pdfOption);
//}
//else
//{
// await Content.RenderToStreamAsync(stream);
//}
}
public async Task PreparePageAsync()
{
await Content.PreparePageAsync();
}
//public async Task<BitmapImage> GetBitmapAsync()
//{
// var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
// await RenderToStreamAsync(stream);
// var result = new BitmapImage();
// await result.SetSourceAsync(stream);
// return result;
//}
public Task<bool> UpdateRequiredAsync(double width, double height)
{
//if (LastOption != null && Option != null && (LastOption.TargetHeight * 1.3 < Option.TargetHeight || LastOption.TargetWidth * 1.3 < Option.TargetWidth))
//if (LastOption != null && Option != null)
if (LastPdfOption == null || (LastPdfOption.DestinationHeight < height * RenderScaleMinimum && LastPdfOption.DestinationWidth < width * RenderScaleMinimum))
{ return Task.FromResult(true); }
else { return Task.FromResult(false); }
}
public async Task<bool> SaveImageAsync(StorageFile file, uint width, Windows.Foundation.Rect? croppedRegionRelative = null)
{
var pdfOption = new pdf.PdfPageRenderOptions
{
DestinationWidth = width
};
if (croppedRegionRelative.HasValue)
{
pdfOption.SourceRect
= new Windows.Foundation.Rect(croppedRegionRelative.Value.X * Content.Size.Width, croppedRegionRelative.Value.Y * Content.Size.Height, croppedRegionRelative.Value.Width * Content.Size.Width, croppedRegionRelative.Value.Height * Content.Size.Height);
}
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
await Content.RenderToStreamAsync(stream, pdfOption);
await Functions.SaveStreamToFile(stream, file);
return true;
}
public async Task<bool> SetBitmapAsync(BitmapSource image, double width, double height)
{
var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
await RenderToStreamAsync(stream, width, height);
if (image is not null) await image.SetSourceAsync(stream);
return true;
}
}
}