zoukankan      html  css  js  c++  java
  • 使用iText 7读取PDF文件中的文本和图片

    读取文本

    using (PdfReader reader = new PdfReader(fileName))
                {
                    using (PdfDocument pdfDocument = new PdfDocument(reader))
                    {
                        for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
                        {
                            string pdfContentString = PdfTextExtractor.GetTextFromPage(pdfDocument.GetPage(i));
                            MessageBox.Show(pdfContentString);
                        }
                    }
                }

    读取图片

    using (PdfReader reader = new PdfReader(fileName))
                {
                    using (PdfDocument pdfDocument = new PdfDocument(reader))
                    {                    
                        IEventListener strategy = new ImageRenderListener(imageFileName);
                        PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);
                        for (var i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
                        {
                            parser.ProcessPageContent(pdfDocument.GetPage(i));
                        }
                    }
                }
    
    
    public class ImageRenderListener : IEventListener
        {
            string format;
            int index = 0;
            public ImageRenderListener(string format)
            {
                this.format = format;
            }
    
            public void EventOccurred(IEventData data, EventType type)
            {
                if (data is ImageRenderInfo imageData)
                {
                    try
                    {
                        PdfImageXObject imageObject = imageData.GetImage();
                        if (imageObject != null)
                        {
                            File.WriteAllBytes(string.Format(format, index++, imageObject.IdentifyImageFileExtension()), imageObject.GetImageBytes());
                        }
                    }
                    catch
                    {                    
                    }
                }
            }
    
            public ICollection<EventType> GetSupportedEvents()
            {
                return null;
            }
        }
  • 相关阅读:
    京东优惠叠加的获取
    树莓派安装omv
    树莓派 omv 安装 nextcloud
    Nginx 502 bad gateway问题的解决方法
    mvc 前台传入后台
    关于cefsharp 获取js动态加载后的信息
    c# 使用 java的 rsa 进行签名
    树莓派基本设置
    树莓派安装raspbian
    winform界面设计
  • 原文地址:https://www.cnblogs.com/Farseer1215/p/15226603.html
Copyright © 2011-2022 走看看