0

I used this code but not getting correct format Image. give better way to convert pdf to Image using iTextsharp.

FileStream fs = File.OpenRead(ImagePath);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
iTextSharp.text.pdf.PdfObject PDFObj = null;
iTextSharp.text.pdf.PdfStream PDFStremObj = null;
try
{
    RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(data);
    PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

    for (int k = 0; k <= PDFReaderObj.XrefSize - 1; k++)
    {
        PDFObj = PDFReaderObj.GetPdfObject(k);
        if ((PDFObj != null) && PDFObj.IsStream())
        {
            PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
            iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
            
            if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
            {
                byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);
                if ((bytes != null))
                {
                    try
                    {
                         System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);
                         MS.Position = 0;
                        System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);
                        ImgList.Add(ImgPDF);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
    }
    PDFReaderObj.Close();
}
catch (Exception ex) { throw ex; }
}
                

above coded getting file from ImagePath using FileStream to pdfobject and then memorystream to Image.

gurkan
  • 884
  • 4
  • 16
  • 25
Sudhir
  • 9
  • 1
  • 8
  • https://stackoverflow.com/questions/518878/how-to-render-pdfs-using-c-sharp ? – Caius Jard Jan 16 '21 at 08:52
  • Thanks @CaiusJard your solution, want solution using iTextSharp only. – Sudhir Jan 16 '21 at 09:42
  • You're gonna struggle then! https://stackoverflow.com/questions/2714905/can-itextsharp-rasterize-export-to-jpeg-or-other-image-format – Caius Jard Jan 16 '21 at 09:50
  • above code working for image conversion but image not converting exactly as it is pdf file. – Sudhir Jan 16 '21 at 10:11
  • Your code does look for bitmap images embedded in the pdf and then attempts to read those embedded bitmaps using `System.Drawing.Image` which often will work in case of embedded jpegs and jp2000 but usually will fail for other formats. – mkl Jan 16 '21 at 22:04

0 Answers0