Created
March 13, 2017 12:06
-
-
Save SuperJMN/e8cb706c3bf1300753c2ecfbd93ce84a to your computer and use it in GitHub Desktop.
UWP useful fragments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Windows.UI.Xaml; | |
namespace IbercajaPay.UWP.Controls | |
{ | |
using System.Collections.ObjectModel; | |
using System.Reactive.Linq; | |
using System.Threading.Tasks; | |
using Windows.Data.Pdf; | |
using Windows.Storage; | |
using Windows.Storage.Streams; | |
using Windows.UI.Xaml.Media.Imaging; | |
public sealed partial class PdfViewer | |
{ | |
public PdfViewer() | |
{ | |
this.InitializeComponent(); | |
Unloaded += OnUnloaded; | |
} | |
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register( | |
"Uri", typeof(Uri), typeof(PdfViewer), new PropertyMetadata(default(Uri), OnSourceChangedAsync)); | |
private static IDisposable imageAdder; | |
private static async void OnSourceChangedAsync(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) | |
{ | |
var target = (PdfViewer)dependencyObject; | |
var targetSource = target.Source; | |
if (targetSource == null) | |
{ | |
return; | |
} | |
var pdf = await GetPdfDocument(targetSource); | |
var imageObs = PdfPages(pdf) | |
.ToObservable() | |
.SelectMany(GetBitmapFromPage); | |
imageAdder = imageObs | |
.ObserveOnDispatcher() | |
.Subscribe(image => target.Bitmaps.Add(image)); | |
} | |
private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs) | |
{ | |
imageAdder?.Dispose(); | |
Unloaded -= OnUnloaded; | |
} | |
private static IEnumerable<PdfPage> PdfPages(PdfDocument pdf) | |
{ | |
for (uint i = 0; i < pdf.PageCount; i++) | |
{ | |
yield return pdf.GetPage(i); | |
} | |
} | |
public ObservableCollection<BitmapSource> Bitmaps { get; } = new ObservableCollection<BitmapSource>(); | |
private static async Task<PdfDocument> GetPdfDocument(Uri uri) | |
{ | |
var stream = await StorageFile.CreateStreamedFileFromUriAsync("temp.pdf", uri, null); | |
var doc = await PdfDocument.LoadFromStreamAsync(await stream.OpenReadAsync()); | |
return doc; | |
} | |
private static async Task<BitmapImage> GetBitmapFromPage(PdfPage page) | |
{ | |
var bitmapImage = new BitmapImage(); | |
using (var pageStream = new InMemoryRandomAccessStream()) | |
{ | |
await page.RenderToStreamAsync(pageStream); | |
await bitmapImage.SetSourceAsync(pageStream); | |
} | |
return bitmapImage; | |
} | |
public Uri Source | |
{ | |
get { return (Uri)GetValue(SourceProperty); } | |
set { SetValue(SourceProperty, value); } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment