In UWP application the requirement is to display PDF Files. For small PDFs below 2 MB or UP to 100 pages, the application works fine. If PDF is size is big and has more number of pages then the application throws out of memory exception. The exception is mainly because in UWP to display PDF we need to render each PDFpage to image format so if pages are more then images collection is increased so having out of memory exception.
How to handle this scenario?
public async static Task<ObservableCollection<BitmapImage>> LoadPdf(PdfDocument pdfDoc)
{
try
{
ObservableCollection<BitmapImage> pdfPages = new ObservableCollection<BitmapImage>();
for (uint i = 0; i < pdfDoc.PageCount; i++)
{
BitmapImage image = new BitmapImage();
var page = pdfDoc.GetPage(i);
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await page.RenderToStreamAsync(stream);
await image.SetSourceAsync(stream);
}
pdfPages.Add(image);
}
return pdfPages;
}
catch (Exception ex)
{
return null;
}
}