- 使用C#提取PDF附件
- 使用C#将附件添加到PDF
- 使用C#从PDF删除附件
.NET的
17周年庆来啦!整合所有格式API处理控件Aspose.Total永久授权火热促销中,新购乐享85折起!联系客服立马1分钟了解全部!
使用C#提取PDF附件
首先,让我们看看如何从PDF文档中检索附件。为此,请按照以下步骤操作:
- 创建Document类的实例。
- 使用Document.EmbeddedFiles属性将附件获取到EmbeddedFileCollection对象中。
- 使用FileSpecification对象遍历EmbeddedFileCollection中的附件。
- 使用FileSpecification对象访问每个附件的属性。
- 将附件另存为文件(如果需要)。
下面的代码示例演示如何使用C#提取PDF附件。
// Open documentDocument pdfDocument = new Document("document.pdf");// Get particular embedded fileforeach(FileSpecification fileSpecification in pdfDocument.EmbeddedFiles){ // Get the file properties Console.WriteLine("Name: {0}", fileSpecification.Name); Console.WriteLine("Description: {0}", fileSpecification.Description); Console.WriteLine("Mime Type: {0}", fileSpecification.MIMEType); // Check if parameter object contains the parameters if (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 stream byte[] 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 documentDocument pdfDocument = new Document("document.pdf");// Setup new file to be added as attachmentFileSpecification fileSpecification = new FileSpecification("test.txt", "Sample text file");// Add attachment to document's attachment collectionpdfDocument.EmbeddedFiles.Add(fileSpecification);// Save new outputpdfDocument.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 documentDocument pdfDocument = new Document("document.pdf");// Delete all attachmentspdfDocument.EmbeddedFiles.Delete();// Save updated filepdfDocument.Save("output.pdf");
还想要更多吗可以点击阅读【2020 · Aspose最新资源整合】,查找需要的教程资源。如果您有任何疑问或需求,请随时加入Aspose技术交流群(),我们很高兴为您提供查询和咨询。
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!