Search code examples
c#arraylistwebformsitextpdf-generation

Generate PDF with iTextSharp - multiple images saved in List<string> - C#


I have an asp.net webform project where I generate a pdf document from data that is saved in a database using iTextSharp. Everything works perfectly, except when I need to generate my images, saved in a List string. I put a breakpoint, I am reading the data, but every time it throws me errors in the part Image.GetInstance(item). If I left it like that, it throws me an error the System.IO.PathTooLongException: 'The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.' I have also tried to convert the item to string, but then it says that the path could not be found. I even tried to convert the whole list to List byte, but I came up with the same errors. My List string in the database looks something like this format:

ImgList: ["904u3jg8orut390jgg","09re8im09mj3895gh","509tgj390h359"].

I tried and googled the errors each and every one of them, but I could not find a solution. I have even tried to enable longpath in Windows, but it did not work for me. If someone could help me, I would be very grateful. Here is my code.

EDIT: I think that the problem is with the splitting and replacing the characters. When I add the string to the list, I am getting an extra quotes and backslash, wrapped in like this "\"... \"". I have tried to trim, to replace the characters but nothing successful. I have tried to change the imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList(); with imgList = imgList.Select(s => s.Replace("\\b\"", string.Empty)).ToList(); but it did not work. Any help?

 //getting data from database
 string strList = dt.Rows[0]["imgList"].ToString();
 List<string> imgList = new List<string>(strList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
 imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList();
 imgList = imgList.Select(s => s.Replace("[", string.Empty)).ToList();
 imgList = imgList.Select(s => s.Replace("]", string.Empty)).ToList();
 
//assign the value
pdf.ImageList = imgList;

//using iTextSharp  
  foreach (var item in pdf.ImageList)
        {
           if (item.Count() >= 1)
               {
            Image image = Image.GetInstance(item);
           }
         }

Solution

  • In a comment you mentioned:

    those images are uploaded, HttpPostedFile in byte[] from Binary Reader and converted ToBase64String the byte[]

    So those images are base64-encoded... consequentially you have to base64-decode the database contents again to get the image byte arrays. Then you can feed those image byte arrays into Image.GetInstance.