0

I would like to convert a PDF to a Bitmap, so I can show it on my ASP.NET page. But when I run my code it fails at creating the Bitmap.

Does anyone know what's the problem?

string filepath = "C:\\Temp\\Sample.pdf";


byte[] pdfByte = File.ReadAllBytes(filepath);
var strBase64 = Convert.ToBase64String(pdfByte);

using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(strBase64)))
{
    using (Bitmap bm2 = new Bitmap(ms))
    {
        bm2.Save("c:\\" + "test");
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
sarah
  • 9
  • 1
    Pretty sure you can't just read the bytes of a PDF and have it convert into a Bitmap like that... I only know of third part libraries that can accomplish this for you. Someone correct me if I'm wrong because I'll learn something new! :-) (P.S it would help if you posted the error you receive...) – Equalsk Feb 04 '16 at 13:46
  • 2
    Why would you expect that going via base64 would help? A PDF simply isn't an image... You're basically passing `pdfByte` to the `MemoryStream` constructor. – Jon Skeet Feb 04 '16 at 13:47
  • This question is based on a fundamental misunderstanding. The base64 roundtrip is not necessary, but the main problem is that you can't just pass arbitrary bytes to a `Bitmap()` constructor; that byte array must already represent an image in a known image format. You'll need some software that knows how to read and render a PDF, then render that to an image. See for example [Convert PDF to Image without using Ghostscript DLL](http://stackoverflow.com/questions/12831742/convert-pdf-to-image-without-using-ghostscript-dll), first Google hit for "C# pdf to image". – CodeCaster Feb 04 '16 at 13:48

0 Answers0