I am creating a Windows store application (formerly called Metro app) that is able to read in and display several different file types (jpg, wmv, pdf, etc). Each file type is displayed using the appropriate XAML control (eg. jpg uses Image and wmv uses MediaElement). A problem I have come across is displaying PDFs. It seems I will have to convert it to an image to display. I have investigated using Magick.NET but that targets .NETFramework rather than .NETCore. Other frameworks I have sought out require a license. Is there a solution to display a PDF within my application?
After watching the first 10 minutes of the video provided by Nate Diamond, rendering a PDF is a simple task. This is a solution for Windows 8.1 as the PdfDocument and PdfPage classes are new to the version. Below renders a StorageFile (which is a .pdf file) into images and puts them into a vertically scrolling stack panel (imagePanel).
private async void renderPdf(StorageFile file)
{
imagePanel.Children.Clear();
PdfDocument pdf = await PdfDocument.LoadFromFileAsync(file);
for (uint pageNum = 0; pageNum < pdf.PageCount; pageNum++)
{
PdfPage page = pdf.GetPage(pageNum);
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
await page.RenderToStreamAsync(stream);
BitmapImage source = new BitmapImage();
source.SetSource(stream);
Image pdfPage = new Image();
pdfPage.HorizontalAlignment = HorizontalAlignment.Center;
pdfPage.VerticalAlignment = VerticalAlignment.Center;
pdfPage.Height = page.Size.Height;
pdfPage.Width = page.Size.Width;
pdfPage.Margin = new Thickness(0, 0, 0, 5);
pdfPage.Source = source;
imagePanel.Children.Add(pdfPage);
}
}
The asynchronous methods can also be ran as tasks if awaiting is undesirable.
PdfDocument pdf = PdfDocument.LoadFromFileAsync(file).AsTask().Result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With