saifullah khan

saifullah khan

  • NA
  • 335
  • 300.9k

Pass string[] to merge images to pdf ASP.NET

Mar 23 2018 1:40 AM
I'm trying to merg images from a folder to a pdf file. here is my code:
  1. /// <summary>    
  2. /// Takes a collection of BMP files and converts them into a PDF document    
  3. /// </summary>    
  4. /// <param name="bmpFilePaths"></param>    
  5. /// <returns></returns>    
  6. private byte[] CreatePdf(string[] bmpFilePaths)    
  7. {    
  8.     using (var ms = new MemoryStream())    
  9.     {    
  10.         var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);    
  11.         iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();    
  12.         document.Open();    
  13.         foreach (var path in bmpFilePaths)    
  14.         {    
  15.             var imgStream = GetImageStream(path);    
  16.             var image = iTextSharp.text.Image.GetInstance(imgStream);    
  17.             image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);    
  18.             document.Add(image);    
  19.         }    
  20.         document.Close();    
  21.         return ms.ToArray();    
  22.     }    
  23. }    
  24.     
  25. /// <summary>    
  26. /// Gets the image at the specified path, shrinks it, converts to JPG, and returns as a stream    
  27. /// </summary>    
  28. /// <param name="imagePath"></param>    
  29. /// <returns></returns>    
  30. private Stream GetImageStream(string imagePath)    
  31. {    
  32.     var ms = new MemoryStream();    
  33.     using (var img = Image.FromFile(imagePath))    
  34.     {    
  35.         var jpegCodec = ImageCodecInfo.GetImageEncoders()    
  36.             .Where(x => x.MimeType == "image/jpeg")    
  37.             .FirstOrDefault();    
  38.      
  39.         var encoderParams = new EncoderParameters(1);    
  40.         encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)20);    
  41.      
  42.         int dpi = 175;    
  43.         var thumb = img.GetThumbnailImage((int)(11 * dpi), (int)(8.5 * dpi), null, IntPtr.Zero);    
  44.         thumb.Save(ms, jpegCodec, encoderParams);    
  45.     }    
  46.     ms.Seek(0, SeekOrigin.Begin);    
  47.     return ms;    
  48. }   
The images are in a folder. can somebody please tell me how to pass string[] with the list of images links to CreatePdf(string[] bmpFilesPath) from a button click function.

Answers (1)