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处理能力。

相关内容

热门资讯

第8分钟大纲!雀姬手游透视辅助... 第8分钟大纲!雀姬手游透视辅助(外挂)一直真的有辅助插件(哔哩哔哩)1、下载好雀姬手游透视辅助透视辅...
现就发布提示!掌电竞技辅助工具... 现就发布提示!掌电竞技辅助工具"切实存在有辅助软件"(哔哩哔哩)运掌电竞技辅助工具辅助工具,进入游戏...
第7分钟了解!德普之星辅助器a... 第7分钟了解!德普之星辅助器app(脚本)本来是真的辅助神器(哔哩哔哩)1、德普之星辅助器app有没...
2026版辅助挂!上饶打炸辅助... 2026版辅助挂!上饶打炸辅助"总是真的是有辅助攻略"(哔哩哔哩)1、2026版辅助挂!上饶打炸辅助...
3分钟了解!wepoker辅助... 3分钟了解!wepoker辅助器激活码(脚本)其实有辅助挂(哔哩哔哩)1、游戏颠覆性的策略玩法,独创...
4分钟经验!心动休闲辅助(外挂... 4分钟经验!心动休闲辅助(外挂)果然有辅助技巧(哔哩哔哩)所有人都在同一条线上,像星星一样排成一排,...
9分钟了解!hhpoker破解... 9分钟了解!hhpoker破解工具(脚本)切实真的是有辅助器(哔哩哔哩)1、实时hhpoker破解工...
近期!超凡辅助app链接&qu... 近期!超凡辅助app链接"好像存在有辅助器"(哔哩哔哩)1、起透看视 超凡辅助app链接辅助软件价格...
第七分钟教程书!微乐四川麻将辅... 第七分钟教程书!微乐四川麻将辅助器(外挂)原来存在有辅助方法(哔哩哔哩)1、完成微乐四川麻将辅助器有...
第三分钟了解!wpk软件是正规... 第三分钟了解!wpk软件是正规的吗(脚本)一直存在有辅助技巧(哔哩哔哩)1、首先打开wpk软件是正规...