c# – 使用itextsharp从PDF中提取图像

前端之家收集整理的这篇文章主要介绍了c# – 使用itextsharp从PDF中提取图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用itextsharp从pdf中提取所有图像,但似乎无法克服这一个障碍.

System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS)上的错误发生.给出“参数无效”的错误.

我认为它是有效的,当图像是位图,但没有任何其他格式.

我有以下代码 – 对不起长度;

  1. private void Form1_Load(object sender,EventArgs e)
  2. {
  3. FileStream fs = File.OpenRead(@"reader.pdf");
  4. byte[] data = new byte[fs.Length];
  5. fs.Read(data,(int)fs.Length);
  6.  
  7. List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();
  8.  
  9. iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
  10. iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
  11. iTextSharp.text.pdf.PdfObject PDFObj = null;
  12. iTextSharp.text.pdf.PdfStream PDFStremObj = null;
  13.  
  14. try
  15. {
  16. RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(data);
  17. PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj,null);
  18.  
  19. for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
  20. {
  21. PDFObj = PDFReaderObj.GetPdfObject(i);
  22.  
  23. if ((PDFObj != null) && PDFObj.IsStream())
  24. {
  25. PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
  26. iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
  27.  
  28. if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
  29. {
  30. byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);
  31.  
  32. if ((bytes != null))
  33. {
  34. try
  35. {
  36. System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);
  37.  
  38. MS.Position = 0;
  39. System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);
  40.  
  41. ImgList.Add(ImgPDF);
  42.  
  43. }
  44. catch (Exception)
  45. {
  46. }
  47. }
  48. }
  49. }
  50. }
  51. PDFReaderObj.Close();
  52. }
  53. catch (Exception ex)
  54. {
  55. throw new Exception(ex.Message);
  56. }
  57.  
  58.  
  59.  
  60. } //Form1_Load

解决方法

我过去一直使用这个图书馆,没有任何问题.这应该是你正在追求的.

http://www.winnovative-software.com/PdfImgExtractor.aspx

猜你在找的C#相关文章