Press "Enter" to skip to content

Browsing pdf’s on the raspberry pi II

Couple of days ago a colleague started a question with “wouldn’t it be cool if..”. This kind of start will always mean that:

  1. It’s something off the books
  2. It eat up your spare time
  3. You can’t ignore it, cause it’s too cool

That’s exactly what happened. He asked me “wouldn’t it be cool if we could use the raspberry pi 2 to view our monitoring systems”. Yes that would be cool, but there is one problem. Those monitoring system rely on pdf’s with information and the WebView xaml control doesn’t support pdf.

I tried the IoTBrowser sample from github, but as expected, didn’t show the pdf. A quick look around didn’t get me any further so I posted a question on the repository for the iot samples. I didn’t expect an answer any time soon, but I was proven otherwise. A couple of hours later a got a reply with a hint to Windows.Data.Pdf. I started to play with this namespace and ended up with a working sample, this is the code:

private async void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    if (args.Uri.AbsolutePath.EndsWith(".pdf"))
            // 1. Download the pdf
            var getPdfHttpClient = new HttpClient();
            var pdf = await getPdfHttpClient.GetByteArrayAsync(args.Uri.AbsoluteUri);

            // 2. Store it in a temp file
            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            StorageFile pdfFileOriginal = await folder.CreateFileAsync(Guid.NewGuid().ToString() + ".pdf");

            using (IRandomAccessStream pdfFileStream = await pdfFileOriginal.OpenAsync(FileAccessMode.ReadWrite))
                await pdfFileStream.WriteAsync(pdf.AsBuffer());
                await pdfFileStream.FlushAsync();

            // 3. Load pdf as PdfDocument
            var _pdfDoc = await PdfDocument.LoadFromFileAsync(pdfFileOriginal);

            // 4. Create png file
            StorageFile pngFileOriginal = await folder.CreateFileAsync(Guid.NewGuid().ToString() + ".png");

            // 5. As a test, only show first page
            using (IRandomAccessStream pngFileStream = await pngFileOriginal.OpenAsync(FileAccessMode.ReadWrite))
                await _pdfDoc.GetPage(0).RenderToStreamAsync(pngFileStream);
                await pngFileStream.FlushAsync();

            // 6. Set image as source for xaml image
            pdfImage.Source = new BitmapImage(new Uri(pngFileOriginal.Path, UriKind.Absolute));
        catch (Exception ex)