【发布时间】:2016-06-22 23:51:23
【问题描述】:
我想从 PDF 文件中提取图像。我尝试使用以下代码,它完美地从 PDF 中提取了 jpeg 图像。问题是如何从特定页面中提取图像,例如第 1 页或其他页面。我不想阅读整个 PDF 来搜索图片。
有什么建议吗?
图像提取代码:
private void List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
{
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(PDFSourcePath);
PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);
for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
{
PDFObj = PDFReaderObj.GetPdfObject(i);
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);
pictureBox1.Image = ImgPDF;
MS.Close();
MS.Flush();
}
catch (Exception)
{
}
}
}
}
}
PDFReaderObj.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
【问题讨论】:
-
这与手头的问题无关,但我想我会指出:
throw new Exception(ex.Message);不会重新抛出异常,而是创建一个新异常并导致堆栈丢失跟踪信息。只需使用throw;,除非这是您明确想要达到的效果。 -
@harriyott:你没有明白我的意思。我想指定它应该搜索图像的页码。
-
itextsharp extract images 的可能重复项
-
@ChrisHaas:先生,我只想指定要阅读的页码。现在它正在阅读完整的 PDF 并从中搜索图像。
-
@ChrisHaas: RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath); PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);在上面你可以看到它的阅读我只想知道一些指定页面的方法,以便它只阅读特定页面
标签: c# pdf itextsharp