Freigeben über


Display PDF document from WPF/Desktop app on Windows 10

Hi!

There are many PDF libraries out there for displaying PDF documents (some very expensive, personally I prefer Xfinium), but Windows 10 and .NET have built in classes for this. You can't do much except display a bitmap of the pages but this is often all you need. Here's how to do it from a WPF app.

// Call UWP APIs from
// https://blogs.msdn.microsoft.com/lucian/2015/10/23/how-to-call-uwp-apis-from-a-desktop-vbc-app (NuGet UWPDesktop)

// AsRandomAccessStream from
// https://stackoverflow.com/questions/7669311/is-there-a-way-to-convert-a-system-io-stream-to-a-windows-storage-streams-irando

private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
using (var stream = File.OpenRead(@"x.pdf"))

{
var doc = await PdfDocument.LoadFromStreamAsync(stream.AsRandomAccessStream());
var page = doc.GetPage(0);
using (var mem = new MemoryStream())
{
await page.RenderToStreamAsync(mem.AsRandomAccessStream());
var bitmap = BitmapFrame.Create(mem, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
image.Source = bitmap;
}
}
}

Enjoy!
Paul Tallett, UX Global Practice, Microsoft UK

Disclaimer: The information on this site is provided AS IS with no warranties, confers no rights, and is not supported by the authors or Microsoft Corporation. Use of included script samples are subject to the terms specified in the Terms of Use.