0

I have a few PDFs loaded into a List of Byte[] arrays. I want to display the first page of these PDFs inside a WPF form. If possible, an image control would be fine. However, I'd like to stay away from having to write the Bytes out to PDF files on the local machine.

Question: How can I take the Byte[] of a PDF (already in memory), and display the first page of the PDF in an image control without writing PDF to the local machine?

TyCox94
  • 405
  • 1
  • 8
  • 18

1 Answers1

2

You're not going to have to write the PDF to disk, you can keep it in memory. You will however need to fully load the PDF as an object in Memory.

Here's a Microsoft article on how to convert a PDF images in C# using, and I think this would be a good starting point for you. The following example is from the below link, and for your requirements you would skip the for loop and just convert the first page. Note, that when instantiating the PdfImageConverter object, there are multiple overloads, one takes in a stream, which is your byte[].

PdfImageConverter pdfConverter = new PdfImageConverter("sample.pdf"); 

pdfConverter.DPI = 96; 

for (int i = 0; i < pdfConverter.PageCount; i++) 
{    
    Image pageImage = pdfConverter.PageToImage(i, 500, 800); 

    pageImage.Save("Page " + i + ".jpg", ImageFormat.Jpeg); 
}

https://code.msdn.microsoft.com/windowsdesktop/How-to-Convert-PDF-to-84ac3273


Code project has an answer for creating thumbnails from PDF (VB.NET)

https://www.codeproject.com/Articles/5887/Generate-Thumbnail-Images-from-PDF-Documents

It's written in VB.NET but the process will be the same for C#.


There is also another SO question about turning a PDF into images which would also work for you:

Save pdf to jpeg using c#

Do you have any types of requirements (libraries, api's, etc.) that also might affect the solution? If so I will update this answer.

Ryan Ternier
  • 8,714
  • 4
  • 46
  • 69