Search code examples
c#xamlwindows-store-appsmicrosoft-metrowinrt-xaml-toolkit

Can't save PdfPage as a BitmapImage to disk


I'm trying to save the pages of a PdfDocument into the disk as a set of BitmapImage's, for which I'm using the extensions provided by WinRTXamlToolkit.

PdfPage page = pdfd.GetPage(0); // pdfd is a loaded PdfDocument
InMemoryRandomAccessStream str=new InMemoryRandomAccessStream();
await page.RenderToStreamAsync(str);
BitmapImage bmp = new BitmapImage();
await bmp.SetSourceAsync(str);

WriteableBitmap wb = await WriteableBitmapFromBitmapImageExtension.FromBitmapImage(bmp);

StorageFolder sfo;
sfo = await KnownFolders.DocumentsLibrary.CreateFolderAsync("PDFasBMP", CreationCollisionOption.OpenIfExists);

await WriteableBitmapSaveExtensions.SaveToFile(wb,sfo,"Yahooo.bmp");

The output "Yahooo.bmp" is an unreadable 58-bytes file. What am I missing ? The problem has nothing to do with the WinRTXamlToolkit as when the BitmapImage is set to an image in the web it is saved to the disk properly, so the problem is with how the PdfPage works.


Solution

  • Skip the BitmapImage and load your PDF directly into the WriteableBitmap:

    WriteableBitmap wb = new WriteableBitmap(1,1);
    await wb.SetSourceAsync(str);
    

    It's not possible to extract the pixels from a BitmapImage, so WriteableBitmapFromBitmapImageExtension.FromBitmapImage has has to get the data from elsewhere: it works when the BitmapImage is loaded from the web since FromBitmapImage can get the BitmapImage's UriSource and load that URI into the WriteableBitmap.