两个相同的网站对做优化有帮助/今日军事新闻视频
PDF格式支持添加附件,以类似电子邮件附件的PDF文件。PDF附件可以是TXT,DOCX,XLSX或任何其他文档格式。在本文中,您将学习如何在.NET应用程序中实现一些基本的PDF附件操纵功能,即使用C#以编程方式提取,添加或删除PDF中的附件。
- 使用C#提取PDF附件
- 使用C#将附件添加到PDF
- 使用C#从PDF删除附件
.NET的Aspose.PDF是著名的PDF操作API,可让您无缝处理PDF文件。您可以在几个步骤中阅读,创建,编辑和转换PDF文件以及操作PDF附件。(点击下载)
使用C#提取PDF附件
首先,让我们看看如何从PDF文档中检索附件。为此,请按照以下步骤操作:
- 创建Document类的实例。
- 使用Document.EmbeddedFiles属性将附件获取到EmbeddedFileCollection对象中。
- 使用FileSpecification对象遍历EmbeddedFileCollection中的附件。
- 使用FileSpecification对象访问每个附件的属性。
- 将附件另存为文件(如果需要)。
下面的代码示例演示如何使用C#提取PDF附件。
// Open document Document pdfDocument = new Document("document.pdf");// Get particular embedded file foreach(FileSpecification fileSpecification in pdfDocument.EmbeddedFiles) {// Get the file propertiesConsole.WriteLine("Name: {0}", fileSpecification.Name);Console.WriteLine("Description: {0}", fileSpecification.Description);Console.WriteLine("Mime Type: {0}", fileSpecification.MIMEType);// Check if parameter object contains the parametersif (fileSpecification.Params != null){Console.WriteLine("CheckSum: {0}",fileSpecification.Params.CheckSum);Console.WriteLine("Creation Date: {0}",fileSpecification.Params.CreationDate);Console.WriteLine("Modification Date: {0}",fileSpecification.Params.ModDate);Console.WriteLine("Size: {0}", fileSpecification.Params.Size);}// Get the attachment and write to file or streambyte[] fileContent = new byte[fileSpecification.Contents.Length];fileSpecification.Contents.Read(fileContent, 0, fileContent.Length);FileStream fileStream = new FileStream(fileSpecification.Name, FileMode.Create);fileStream.Write(fileContent, 0, fileContent.Length);fileStream.Close(); }
使用C#将附件添加到PDF
.NET的Aspose.PDF也允许您将附件添加到PDF文件。为此,您只需要使用FileSpecification类将文件添加到Document.EmbeddedFiles集合中。以下是将附件添加到PDF文档的步骤。
- 使用Document类创建一个新的PDF文档。
- 创建FileSpecification类的实例以加载附件文件。
- 使用Document.EmbeddedFiles.Add(FileSpecification)方法添加附件。
- 使用Document.Save(String)方法保存文档。
下面的代码示例演示如何使用C#将附件添加到PDF文档。
// Open document Document pdfDocument = new Document("document.pdf");// Setup new file to be added as attachment FileSpecification fileSpecification = new FileSpecification("test.txt", "Sample text file");// Add attachment to document's attachment collection pdfDocument.EmbeddedFiles.Add(fileSpecification);// Save new output pdfDocument.Save("output.pdf");
使用C#从PDF删除附件
可以从PDF文件中删除全部或特定附件。为此,用于.NET的Aspose.PDF提供了以下方法:
- Delete() –删除所有附件。
- Delete(String fileName) –按名称删除附件。
- DeleteByKey(String Key) –按集合中的键删除附件。
以下是从PDF删除附件的步骤。
- 创建Document类的实例以加载PDF文件。
- 使用Document.EmbeddedFiles.Delete()(或其他删除方法)删除附件。
- 使用Document.Save(String)方法保存文件。
以下代码示例显示了如何从C#中的PDF文件中删除附件。
// Open document Document pdfDocument = new Document("document.pdf");// Delete all attachments pdfDocument.EmbeddedFiles.Delete();// Save updated file pdfDocument.Save("output.pdf");
如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。