在 C# 中使用 MemoryStream 类处理大型 PDF 文件时,您可能会遇到内存限制和问题。在 PDF 文件大小远大于 2.5GB 的情况下,任何限制输入文件大小的解决方案都不起作用。下面的分步指南将教您如何使用高级流在 C# 中处理大型 PDF 文件。
在 C# 中处理大型 PDF 文件的步骤
- 打开 Visual Studio 并创建一个空的 C# 控制台应用程序
- 从 NuGet.org 安装最新版本的 Aspose.PDF for .NET
- 初始化 OptimizedMemoryStream 对象以处理大型 PDF 文件
- 使用 FileStream 加载大尺寸 PDF
- 将 FileStream 字节写入 OptimizedMemoryStream
- 使用基于 InputStream 的构造函数初始化 Document 对象
- 根据您的需要操作或修改 PDF 文档
- 将修改后处理的文档保存到磁盘
当您处理大型 PDF 文档并且受到本地磁盘大小的限制时,您需要一个可以允许使用查找能力加载巨大 PDF 文档的界面。简单的 C# MemoryStream 类在处理巨大的 PDF 文件时由于缺乏查找能力而提供限制并导致高内存问题。使用高级流的解决方案在这个阶段出现了。以下代码片段展示了如何使用高级流在 C# 中加载巨大的 PDF 文件。
用 C# 处理大型 PDF 文件的代码
using System; | |
using System.IO; | |
// Add reference to Aspose.PDF for .NET API | |
// Use following namespace to process large PDF files | |
using Aspose.Pdf; | |
namespace ProcessLargePDFFiles | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Set license before processing large PDF files | |
Aspose.Pdf.License AsposePDFLicense = new Aspose.Pdf.License(); | |
AsposePDFLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
string outFile = @"c:\LargeSizePDF_Processed.pdf"; | |
// Initialize OptimizedMemoryStream object in which large size PDF will be stored for loading | |
OptimizedMemoryStream ms = new OptimizedMemoryStream(); | |
// Read large size PDF document from disk using FileStream | |
using (FileStream file = new FileStream(@"c:\LargeSizePDF.pdf", FileMode.Open, FileAccess.Read)) | |
{ | |
byte[] bytes = new byte[file.Length]; | |
file.Read(bytes, 0, (int)file.Length); | |
// Write large PDF bytes to OptimizedMemoryStream | |
ms.Write(bytes, 0, (int)file.Length); | |
} | |
// Use advanced stream to process large PDF file and load into Document object | |
Document doc = new Document(ms); | |
// Save the output PDF document | |
doc.Save(outFile); | |
} | |
} | |
} |
上面的简单代码片段使您能够处理任意大小的 PDF 文档,而无需将它们存储在本地磁盘上。 Aspose.PDF for .NET 中的 OptimizedMemoryStream 类可以使用 C# 中的内存流加载巨大的 PDF 文档。它定义了一个容量超过标准的 MemoryStream,允许您处理大于 2.5GB 的巨大 PDF 文件。
如果您的 PDF 文档有书签并且您想在 .NET 应用程序中阅读它们,您还可以查看 如何使用 C# 阅读 PDF 书签 上的另一个指南。