Home > database >  Convert PDF to Image Byte array to save to database
Convert PDF to Image Byte array to save to database

Time:10-12

What I am trying to accomplish is allowing my user to upload a PDF. I will then convert that to an Image and get the Images byte array. Below is what I have so far.

PdfDocumentProcessor pdfDocumentProcessor = new PdfDocumentProcessor();
using (MemoryStream ms = new MemoryStream(e.UploadedFile.FileBytes))
{

    pdfDocumentProcessor.LoadDocument(ms);

    for (int i = 1; i <= pdfDocumentProcessor.Document.Pages.Count; i  )
    {
        Bitmap image = pdfDocumentProcessor.CreateBitmap(i, 1000);

        try
        {
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        }
        catch (Exception error)
        {
            string message = error.Message;
        }
 }

When I try to save the Image to the memory stream I am getting the error "A generic error occurred in GDI " I believe this has something to do with me not specifying a path for the image to be saved to, but I could be mistaken.

I want to convert the PDF to and Image, then get the byte array of the image, and save that to the database. I really don't want to save the image to a specified path.

PDFDocumentProcessor is a DevExpress class that pulls in the PDF and also will give me the PDF's byte array, but I just can't seem to find a way past the save error to retrieve an Image byte array

Any help is appreciated thank you

CodePudding user response:

The issue is likely caused by you trying to re-use the same MemoryStream that is holding the input file bytes. You should create a new memory stream to save to.

I don't have access to devexpress but I grabbed another Nuget package that i am associated with https://www.nuget.org/packages/Leadtools.Pdf/ and tested it and this code works to save the PDF to a PNG memorystream:

using (var ms = new MemoryStream(fileBytes))
using (var codecs = new RasterCodecs())
{
   codecs.Options.Load.AllPages = true;
   using (var rasterImage = codecs.Load(ms))
   using (var outputStream = new MemoryStream())
      codecs.Save(rasterImage, outputStream, RasterImageFormat.Png, 0);
}
  • Related