使用 itextsharp 从 PDF 中提取图像

发布于 2024-11-05 22:25:55 字数 2449 浏览 0 评论 0原文

我正在尝试使用 itextsharp 从 pdf 中提取所有图像,但似乎无法克服这一障碍。

错误发生在 System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS); 行上,给出“参数无效”错误。

我认为当图像是位图而不是任何其他格式时它会起作用。

我有以下代码 - 抱歉,长度太长了;

    private void Form1_Load(object sender, EventArgs e)
    {
        FileStream fs = File.OpenRead(@"reader.pdf");
        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 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);

                                ImgList.Add(ImgPDF);

                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            PDFReaderObj.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }



    } //Form1_Load

I am trying to extract all the images from a pdf using itextsharp but can't seem to overcome this one hurdle.

The error occures on the line System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS); giving an error of "Parameter is not valid".

I think it works when the image is a bitmap but not of any other format.

I have this following code - sorry for the length;

    private void Form1_Load(object sender, EventArgs e)
    {
        FileStream fs = File.OpenRead(@"reader.pdf");
        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 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);

                                ImgList.Add(ImgPDF);

                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            PDFReaderObj.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }



    } //Form1_Load

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

感性不性感 2024-11-12 22:25:55

已解决...

即使我也遇到了“参数无效”的相同异常,并且经过了这么多
在 der_chirurg 提供的链接的帮助下工作
(http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx)我解决了它
以下是代码:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using iTextSharp.text.pdf;

namespace PDF_Parsing
{
    partial class PDF_ImgExtraction
    {
        string imgPath;
        private void ExtractImage(string pdfFile)
        {
            PdfReader pdfReader = new PdfReader(files[fileIndex]);
            for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
            {
                PdfReader pdf = new PdfReader(pdfFile);
                PdfDictionary pg = pdf.GetPageN(pageNumber);
                PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
                PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        string width = tg.Get(PdfName.WIDTH).ToString();
                        string height = tg.Get(PdfName.HEIGHT).ToString();
                        ImageRenderInfo imgRI = ImageRenderInfo.CreateForXObject(new Matrix(float.Parse(width), float.Parse(height)), (PRIndirectReference)obj, tg);
                        RenderImage(imgRI);
                    }
                }
            }
        }
        private void RenderImage(ImageRenderInfo renderInfo)
        {
            PdfImageObject image = renderInfo.GetImage();
            using (Dotnet dotnetImg = image.GetDrawingImage())
            {
                if (dotnetImg != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        dotnetImg.Save(ms, ImageFormat.Tiff);
                        Bitmap d = new Bitmap(dotnetImg);
                        d.Save(imgPath);
                    }
                }
            }
        }
    }
}

Resolved...

Even I got the same exception of "Parameter is not valid" and after so much of
work with the help of the link provided by der_chirurg
(http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx ) I resolved it
and following is the code:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using iTextSharp.text.pdf;

namespace PDF_Parsing
{
    partial class PDF_ImgExtraction
    {
        string imgPath;
        private void ExtractImage(string pdfFile)
        {
            PdfReader pdfReader = new PdfReader(files[fileIndex]);
            for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
            {
                PdfReader pdf = new PdfReader(pdfFile);
                PdfDictionary pg = pdf.GetPageN(pageNumber);
                PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
                PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        string width = tg.Get(PdfName.WIDTH).ToString();
                        string height = tg.Get(PdfName.HEIGHT).ToString();
                        ImageRenderInfo imgRI = ImageRenderInfo.CreateForXObject(new Matrix(float.Parse(width), float.Parse(height)), (PRIndirectReference)obj, tg);
                        RenderImage(imgRI);
                    }
                }
            }
        }
        private void RenderImage(ImageRenderInfo renderInfo)
        {
            PdfImageObject image = renderInfo.GetImage();
            using (Dotnet dotnetImg = image.GetDrawingImage())
            {
                if (dotnetImg != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        dotnetImg.Save(ms, ImageFormat.Tiff);
                        Bitmap d = new Bitmap(dotnetImg);
                        d.Save(imgPath);
                    }
                }
            }
        }
    }
}
沧桑㈠ 2024-11-12 22:25:55

您需要检查流的 /Filter 以查看给定图像使用的图像格式。它可能是标准图像格式:

  • DCTDecode (jpeg)
  • JPXDecode (jpeg 2000)
  • JBIG2Decode(jbig 是仅限黑白格式)
  • CCITTFaxDecode(传真格式,PDF 支持第 3 组和第 4 组)

除此之外,您还需要获取原始字节(如您所愿),并使用图像流的宽度、高度、每个组件的位数、颜色组件的数量(可以是 CMYK、索引、RGB 或某些奇怪的东西)以及其他一些定义来构建图像在 ISO PDF 规范(免费提供)。

因此,在某些情况下,您的代码可以工作,但在其他情况下,它会因您提到的异常而失败。

PS:当出现异常时,请每次都包含堆栈跟踪。上面加点糖好吗?

You need to check the stream's /Filter to see what image format a given image uses. It may be a standard image format:

  • DCTDecode (jpeg)
  • JPXDecode (jpeg 2000)
  • JBIG2Decode (jbig is a B&W only format)
  • CCITTFaxDecode (fax format, PDF supports group 3 and 4)

Other than that, you'll need to get the raw bytes (as you are), and build an image using the image stream's width, height, bits per component, number of color components (could be CMYK, indexed, RGB, or Something Weird), and a few others, as defined in section 8.9 of the ISO PDF SPECIFICATION (available for free).

So in some cases your code will work, but in others, it'll fail with the exception you mentioned.

PS: When you have an exception, PLEASE include the stack trace every single time. Pretty please with sugar on top?

如果没结果 2024-11-12 22:25:55

使用这两种方法对我来说是这样的:

    public static List<System.Drawing.Image> ExtractImagesFromPDF(byte[] bytes)
    {
        var imgs = new List<System.Drawing.Image>();
        var pdf = new PdfReader(bytes);

        try
        {
            for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
            {
                PdfDictionary pg = pdf.GetPageN(pageNumber);
                List<PdfObject> objs = FindImageInPDFDictionary(pg);

                foreach (var obj in objs)
                {
                    if (obj != null)
                    {
                        int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem = (PdfStream)pdfObj;
                        var pdfImage = new PdfImageObject((PRStream)pdfStrem);
                        var img = pdfImage.GetDrawingImage();

                        imgs.Add(img);
                    }
                }
            }
        }
        finally
        {
            pdf.Close();
        }

        return imgs;
    }

    private static List<PdfObject> FindImageInPDFDictionary(PdfDictionary pg)
    {
        var res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
        var xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
        var pdfObgs = new List<PdfObject>();

        if (xobj != null)
        {
            foreach (PdfName name in xobj.Keys)
            {
                PdfObject obj = xobj.Get(name);
                if (obj.IsIndirect())
                {
                    var tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                    var type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                    if (PdfName.IMAGE.Equals(type)) // image at the root of the pdf
                    {
                        pdfObgs.Add(obj);
                    }
                    else if (PdfName.FORM.Equals(type)) // image inside a form
                    {
                        FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
                    }
                    else if (PdfName.GROUP.Equals(type)) // image inside a group
                    {
                        FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
                    }
                }
            }
        }

        return pdfObgs;
    }

Works for me like this, using these two methods:

    public static List<System.Drawing.Image> ExtractImagesFromPDF(byte[] bytes)
    {
        var imgs = new List<System.Drawing.Image>();
        var pdf = new PdfReader(bytes);

        try
        {
            for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
            {
                PdfDictionary pg = pdf.GetPageN(pageNumber);
                List<PdfObject> objs = FindImageInPDFDictionary(pg);

                foreach (var obj in objs)
                {
                    if (obj != null)
                    {
                        int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem = (PdfStream)pdfObj;
                        var pdfImage = new PdfImageObject((PRStream)pdfStrem);
                        var img = pdfImage.GetDrawingImage();

                        imgs.Add(img);
                    }
                }
            }
        }
        finally
        {
            pdf.Close();
        }

        return imgs;
    }

    private static List<PdfObject> FindImageInPDFDictionary(PdfDictionary pg)
    {
        var res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
        var xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
        var pdfObgs = new List<PdfObject>();

        if (xobj != null)
        {
            foreach (PdfName name in xobj.Keys)
            {
                PdfObject obj = xobj.Get(name);
                if (obj.IsIndirect())
                {
                    var tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                    var type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                    if (PdfName.IMAGE.Equals(type)) // image at the root of the pdf
                    {
                        pdfObgs.Add(obj);
                    }
                    else if (PdfName.FORM.Equals(type)) // image inside a form
                    {
                        FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
                    }
                    else if (PdfName.GROUP.Equals(type)) // image inside a group
                    {
                        FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
                    }
                }
            }
        }

        return pdfObgs;
    }
山川志 2024-11-12 22:25:55

在较新版本的 iTextSharp 中,ImageRenderInfo.CreateForXObject 的第一个参数不再是 Matrix 而是 GraphicsState。 @der_chirurg 的方法应该有效。我使用以下链接中的信息对自己进行了测试,效果非常好:

http://www.thevalvepage.com/swmonkey/2014/11/26/extract-images-from-pdf-files-using-itextsharp/

In newer version of iTextSharp, the 1st parameter of ImageRenderInfo.CreateForXObject is not Matrix anymore but GraphicsState. @der_chirurg's approach should work. I tested myself with the information from the following link and it worked beautifully:

http://www.thevalvepage.com/swmonkey/2014/11/26/extract-images-from-pdf-files-using-itextsharp/

一身仙ぐ女味 2024-11-12 22:25:55

要提取所有页面上的所有图像,无需实现不同的过滤器。 iTextSharp 有一个图像渲染器,它将所有图像保存为其原始图像类型。

只需执行此处找到的以下操作: http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx不需要实现 HttpHandler...

To extract all Images on all Pages, it is not necessary to implement different filters. iTextSharp has an Image Renderer, which saves all Images in their original image type.

Just do the following found here: http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx You don't need to implement HttpHandler...

睫毛上残留的泪 2024-11-12 22:25:55

我在 github 上添加了库,提取 PDF 中的图像并压缩它们。

当您要开始使用非常强大的 ITextSharp 库时,这可能很有用。

链接如下: https://github.com/rock-walker/PdfCompression

I added library on github which, extract images in PDF and compress them.

Could be useful, when you are going to start play with very powerful library ITextSharp.

Here the link: https://github.com/rock-walker/PdfCompression

不语却知心 2024-11-12 22:25:55

这对我有用,我认为这是一个简单的解决方案:

编写一个自定义 RenderListener 并实现其 RenderImage 方法,如下所示

    public void RenderImage(ImageRenderInfo info)
    {
        PdfImageObject image = info.GetImage();
        Parser.Matrix matrix = info.GetImageCTM();
        var fileType = image.GetFileType();
        ImageFormat format;
        switch (fileType)
        {//you may add more types here
            case "jpg":
            case "jpeg":
                format = ImageFormat.Jpeg;
                break;
            case "pnt":
                format = ImageFormat.Png;
                break;
            case "bmp":
                format = ImageFormat.Bmp;
                break;
            case "tiff":
                format = ImageFormat.Tiff;
                break;
            case "gif":
                format = ImageFormat.Gif;
                break;
            default:
                format = ImageFormat.Jpeg;
                break;
        }

        var pic = image.GetDrawingImage();
        var x = matrix[Parser.Matrix.I31];
        var y = matrix[Parser.Matrix.I32];
        var width = matrix[Parser.Matrix.I11];
        var height = matrix[Parser.Matrix.I22];
        if (x < <some value> && y < <some value>)
        {
            return;//ignore these images
        }

        pic.Save(<path and name>, format);
}

This works for me and I think it's a simple solution:

Write a custom RenderListener and implement its RenderImage method, something like this

    public void RenderImage(ImageRenderInfo info)
    {
        PdfImageObject image = info.GetImage();
        Parser.Matrix matrix = info.GetImageCTM();
        var fileType = image.GetFileType();
        ImageFormat format;
        switch (fileType)
        {//you may add more types here
            case "jpg":
            case "jpeg":
                format = ImageFormat.Jpeg;
                break;
            case "pnt":
                format = ImageFormat.Png;
                break;
            case "bmp":
                format = ImageFormat.Bmp;
                break;
            case "tiff":
                format = ImageFormat.Tiff;
                break;
            case "gif":
                format = ImageFormat.Gif;
                break;
            default:
                format = ImageFormat.Jpeg;
                break;
        }

        var pic = image.GetDrawingImage();
        var x = matrix[Parser.Matrix.I31];
        var y = matrix[Parser.Matrix.I32];
        var width = matrix[Parser.Matrix.I11];
        var height = matrix[Parser.Matrix.I22];
        if (x < <some value> && y < <some value>)
        {
            return;//ignore these images
        }

        pic.Save(<path and name>, format);
}
给不了的爱 2024-11-12 22:25:55

我过去使用过这个库,没有任何问题。

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

private void btnExtractImages_Click(object sender, EventArgs e)
{
    if (pdfFileTextBox.Text.Trim().Equals(String.Empty))
    {
        MessageBox.Show("Please choose a source PDF file", "Choose PDF file", MessageBoxButtons.OK);
        return;
    }

    // the source pdf file
    string pdfFileName = pdfFileTextBox.Text.Trim();

    // start page number
    int startPageNumber = int.Parse(textBoxStartPage.Text.Trim());
    // end page number
    // when it is 0 the extraction will continue up to the end of document
    int endPageNumber = 0;
    if (textBoxEndPage.Text.Trim() != String.Empty)
        endPageNumber = int.Parse(textBoxEndPage.Text.Trim());

    // create the PDF images extractor object
    PdfImagesExtractor pdfImagesExtractor = new PdfImagesExtractor();

    pdfImagesExtractor.LicenseKey = "31FAUEJHUEBQRl5AUENBXkFCXklJSUlQQA==";

    // the demo output directory
    string outputDirectory = Path.Combine(Application.StartupPath, @"DemoFiles\Output");

    Cursor = Cursors.WaitCursor;

    // set the handler to be called when an image was extracted
    pdfImagesExtractor.ImageExtractedEvent += pdfImagesExtractor_ImageExtractedEvent;

    try
    {
        // start images counting
        imageIndex = 0;

        // call the images extractor to raise the ImageExtractedEvent event when an images is extracted from a PDF page
        // the pdfImagesExtractor_ImageExtractedEvent handler below will be executed for each extracted image
        pdfImagesExtractor.ExtractImagesInEvent(pdfFileName, startPageNumber, endPageNumber);

        // Alternatively you can use the ExtractImages() and ExtractImagesToFile() methods
        // to extracted the images from a PDF document in memory or to image files in a directory

        // uncomment the line below to extract the images to an array of ExtractedImage objects
        //ExtractedImage[] pdfPageImages = pdfImagesExtractor.ExtractImages(pdfFileName, startPageNumber, endPageNumber);

        // uncomment the lines below to extract the images to image files in a directory
        //string outputDirectory = System.IO.Path.Combine(Application.StartupPath, @"DemoFiles\Output");
        //pdfImagesExtractor.ExtractImagesToFile(pdfFileName, startPageNumber, endPageNumber, outputDirectory, "pdfimage");
    }
    catch (Exception ex)
    {
        // The extraction failed
        MessageBox.Show(String.Format("An error occurred. {0}", ex.Message), "Error");
        return;
    }
    finally
    {
        // uninstall the event handler
        pdfImagesExtractor.ImageExtractedEvent -= pdfImagesExtractor_ImageExtractedEvent;

        Cursor = Cursors.Arrow;
    }

    try
    {
        System.Diagnostics.Process.Start(outputDirectory);
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("Cannot open output folder. {0}", ex.Message));
        return;
    }
}

/// <summary>
/// The ImageExtractedEvent event handler called after an image was extracted from a PDF page.
/// The event is raised when the ExtractImagesInEvent() method is used
/// </summary>
/// <param name="args">The handler argument containing the extracted image and the PDF page number</param>
void pdfImagesExtractor_ImageExtractedEvent(ImageExtractedEventArgs args)
{
    // get the image object and page number from even handler argument
    Image pdfPageImageObj = args.ExtractedImage.ImageObject;
    int pageNumber = args.ExtractedImage.PageNumber;

    // save the extracted image to a PNG file
    string outputPageImage = Path.Combine(Application.StartupPath, @"DemoFiles\Output", 
        "pdfimage_" + pageNumber.ToString() + "_" + imageIndex++ + ".png");
    pdfPageImageObj.Save(outputPageImage, ImageFormat.Png);

    args.ExtractedImage.Dispose();
}

I have used this library in the past without any problems.

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

private void btnExtractImages_Click(object sender, EventArgs e)
{
    if (pdfFileTextBox.Text.Trim().Equals(String.Empty))
    {
        MessageBox.Show("Please choose a source PDF file", "Choose PDF file", MessageBoxButtons.OK);
        return;
    }

    // the source pdf file
    string pdfFileName = pdfFileTextBox.Text.Trim();

    // start page number
    int startPageNumber = int.Parse(textBoxStartPage.Text.Trim());
    // end page number
    // when it is 0 the extraction will continue up to the end of document
    int endPageNumber = 0;
    if (textBoxEndPage.Text.Trim() != String.Empty)
        endPageNumber = int.Parse(textBoxEndPage.Text.Trim());

    // create the PDF images extractor object
    PdfImagesExtractor pdfImagesExtractor = new PdfImagesExtractor();

    pdfImagesExtractor.LicenseKey = "31FAUEJHUEBQRl5AUENBXkFCXklJSUlQQA==";

    // the demo output directory
    string outputDirectory = Path.Combine(Application.StartupPath, @"DemoFiles\Output");

    Cursor = Cursors.WaitCursor;

    // set the handler to be called when an image was extracted
    pdfImagesExtractor.ImageExtractedEvent += pdfImagesExtractor_ImageExtractedEvent;

    try
    {
        // start images counting
        imageIndex = 0;

        // call the images extractor to raise the ImageExtractedEvent event when an images is extracted from a PDF page
        // the pdfImagesExtractor_ImageExtractedEvent handler below will be executed for each extracted image
        pdfImagesExtractor.ExtractImagesInEvent(pdfFileName, startPageNumber, endPageNumber);

        // Alternatively you can use the ExtractImages() and ExtractImagesToFile() methods
        // to extracted the images from a PDF document in memory or to image files in a directory

        // uncomment the line below to extract the images to an array of ExtractedImage objects
        //ExtractedImage[] pdfPageImages = pdfImagesExtractor.ExtractImages(pdfFileName, startPageNumber, endPageNumber);

        // uncomment the lines below to extract the images to image files in a directory
        //string outputDirectory = System.IO.Path.Combine(Application.StartupPath, @"DemoFiles\Output");
        //pdfImagesExtractor.ExtractImagesToFile(pdfFileName, startPageNumber, endPageNumber, outputDirectory, "pdfimage");
    }
    catch (Exception ex)
    {
        // The extraction failed
        MessageBox.Show(String.Format("An error occurred. {0}", ex.Message), "Error");
        return;
    }
    finally
    {
        // uninstall the event handler
        pdfImagesExtractor.ImageExtractedEvent -= pdfImagesExtractor_ImageExtractedEvent;

        Cursor = Cursors.Arrow;
    }

    try
    {
        System.Diagnostics.Process.Start(outputDirectory);
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("Cannot open output folder. {0}", ex.Message));
        return;
    }
}

/// <summary>
/// The ImageExtractedEvent event handler called after an image was extracted from a PDF page.
/// The event is raised when the ExtractImagesInEvent() method is used
/// </summary>
/// <param name="args">The handler argument containing the extracted image and the PDF page number</param>
void pdfImagesExtractor_ImageExtractedEvent(ImageExtractedEventArgs args)
{
    // get the image object and page number from even handler argument
    Image pdfPageImageObj = args.ExtractedImage.ImageObject;
    int pageNumber = args.ExtractedImage.PageNumber;

    // save the extracted image to a PNG file
    string outputPageImage = Path.Combine(Application.StartupPath, @"DemoFiles\Output", 
        "pdfimage_" + pageNumber.ToString() + "_" + imageIndex++ + ".png");
    pdfPageImageObj.Save(outputPageImage, ImageFormat.Png);

    args.ExtractedImage.Dispose();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文