C#处理PDF:深度解析从零开始实现读取PDF文档中的文本和图片
创始人
2024-12-27 19:07:24
0

第1章:准备工作

1.1 环境配置与依赖引入

  • 安装.NET SDK:确保已安装最新版本的.NET SDK,可在Microsoft官网下载安装。

  • 创建项目:使用Visual Studio或CLI工具(如dotnet new console -n PDFReader)创建一个新的C#控制台应用程序。

  • 添加NuGet包:为项目添加PDF处理库的依赖。这里以流行的iTextSharp和ImageSharp库为例:

     Bash 
    dotnet add package iTextSharp --version 5.5.13 dotnet add package SixLabors.ImageSharp --version 2.0.0

第2章:读取PDF文档中的文本

2.1 iTextSharp库简介

iTextSharp是基于iText库的.NET版本,提供了全面的PDF文档操作功能,包括读取、创建、编辑和转换PDF文档。我们将使用iTextSharp来读取PDF中的文本内容。

2.2 读取文本代码示例

 

Csharp

using System; using System.Collections.Generic; using System.IO; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser;  namespace PDFReader {     class Program     {         static void Main(string[] args)         {             string filePath = @"C:\path\to\your\pdf\file.pdf";             var textExtractor = new PdfTextExtractor(filePath);             string extractedText = textExtractor.ExtractText();             Console.WriteLine(extractedText);         }     }      ///      /// Helper class for extracting text from a PDF file.     ///      public class PdfTextExtractor     {         private readonly string _filePath;          public PdfTextExtractor(string filePath)         {             _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));         }          public string ExtractText()         {             using (var reader = new PdfReader(_filePath))             {                 var sb = new StringBuilder();                  for (int i = 1; i <= reader.NumberOfPages; i++)                 {                     var strategy = new SimpleTextExtractionStrategy();                     sb.Append(PdfTextExtractor.ExtractTextFromPage(reader, i, strategy));                 }                  return sb.ToString();             }         }          private static string ExtractTextFromPage(PdfReader reader, int pageNumber, ITextExtractionStrategy strategy)         {             var currentText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, pageNumber, strategy);             return currentText.Trim();         }     } }

第3章:读取PDF文档中的图片

3.1 ImageSharp库简介

ImageSharp是一个跨平台的.NET图像处理库,支持多种图像格式的读写和操作。我们将使用ImageSharp来读取PDF文档中的图片。

3.2 读取图片代码示例

 

Csharp

using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.IO; using iTextSharp.text.pdf; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing;  namespace PDFReader {     class Program     {         static void Main(string[] args)         {             string filePath = @"C:\path\to\your\pdf\file.pdf";             var imageExtractor = new PdfImageExtractor(filePath);             List> images = imageExtractor.ExtractImages();             foreach (var image in images)             {                 image.SaveAsPng($"output_{Guid.NewGuid()}.png");             }         }     }      ///      /// Helper class for extracting images from a PDF file.     ///      public class PdfImageExtractor     {         private readonly string _filePath;          public PdfImageExtractor(string filePath)         {             _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));         }          public List> ExtractImages()         {             var images = new List>();              using (var reader = new PdfReader(_filePath))             {                 for (int i = 1; i <= reader.NumberOfPages; i++)                 {                     images.AddRange(ExtractImagesFromPage(reader, i));                 }             }              return images;         }          private IEnumerable> ExtractImagesFromPage(PdfReader reader, int pageNumber)         {             var resources = reader.GetPageResources(pageNumber);             var xObjects = resources.GetResourceDictionary(PdfName.XObject);              foreach (var entry in xObjects.EntrySet())             {                 PdfObject obj = xObjects.GetDirectObject(entry.Key);                 if (obj.IsIndirect())                 {                     PdfDictionary xObjDict = (PdfDictionary)obj;                     PdfName subtype = xObjDict.GetAsName(PdfName.Subtype);                      if (PdfName.Image.Equals(subtype))                     {                         byte[] imageData = PdfReader.GetStreamBytesRaw((PRStream)xObjDict);                         using var ms = new MemoryStream(imageData);                         var image = Image.Load(ms);                         yield return image;                     }                 }             }         }     } }

第4章:性能优化与最佳实践

  • 批量读取与处理:对于大文件或包含大量图片的PDF,考虑分批次读取和处理,避免一次性加载所有数据导致内存溢出。
  • 异步处理:利用C#的异步编程模型(async/await),将I/O密集型操作异步化,提高程序响应速度。
  • 错误处理与重试机制:对可能出现的文件读取错误、PDF解析异常等进行捕获和适当处理,必要时实现重试机制以增强程序健壮性。

至此,我们已经完成了从零开始使用C#处理PDF文档,深度解析了如何使用iTextSharp和ImageSharp库实现读取PDF中的文本和图片的全流程。提供的代码示例和详细注释旨在帮助您快速理解和应用这些技术,为您的项目提供有效的PDF处理能力。

相关内容

热门资讯

终于知道!wepoker有透视... 终于知道!wepoker有透视底牌吗,微信闲来辅助神器,大纲教程(有挂辅助)1、完成微信闲来辅助神器...
科技分享!wepoker怎么拿... 科技分享!wepoker怎么拿到好牌,大唐麻将开挂软件,举措教程(揭秘有挂)1、玩家可以在大唐麻将开...
值得注意的是!线上德州的辅助器... 值得注意的是!线上德州的辅助器是什么,逗娱碰胡开挂,指南书教程(有挂猫腻)1)逗娱碰胡开挂有没有挂:...
分享认知!epoker免费透视... 分享认知!epoker免费透视脚本,微乐小程序辅助开发,方针教程(有挂功能)微乐小程序辅助开发是不是...
为切实保障!wepoker透视... 为切实保障!wepoker透视底牌脚本,福建13水软件辅助,法门教程(的确有挂)1.福建13水软件辅...
据公告内容!约局吧德州真的存在... 据公告内容!约局吧德州真的存在透视吗,天道手游辅助,手册教程(有挂详情)1、用户打开应用后不用登录就...
科技通报!wepoker游戏下... 科技通报!wepoker游戏下载,免费挂机辅助工具,手册教程(有挂教学)1、操作简单,无需免费挂机辅...
今日科普!wepoker底牌透... 今日科普!wepoker底牌透视脚本,微信小程序多乐辅助器,大纲教程(有挂技巧)1.微信小程序多乐辅...
事发当天!德州透视hhpoke... 事发当天!德州透视hhpoker,微信呢途游四川辅助器,绝活教程(有挂详细)1、玩家可以在微信呢途游...
分享一款!hhpoker德州挂... 分享一款!hhpoker德州挂真的有吗,杭州都莱有没有挂,窍门教程(有挂详细);杭州都莱有没有挂能透...