当前位置: 首页 > news >正文

C# 添加、获取及删除PDF附件

C# 添加、获取及删除PDF附件

前言

附件在PDF文档中很常见,这些附件可以是PDF或其他类型的文件。在PDF中,附件有两种存在方式,一种是普通的文件附件(document-level file attachment),另一种是注释(annotation)。本文主要介绍如何在C#应用程序中给PDF文档添加附件以及从PDF文档获取附件、删除附件。

我们都知道.NET Framework 本身并没有直接操作PDF的类库,因此在.NET应用程序中操作PDF文档必须要借助第三方组件提供的dll。本文主要使用的是Free Spire.PDF组件的dll。

实现

1.  添加附件

以下代码将介绍两种将文档附加到PDF的方式。一种是将文档作为文件附件添加到PDF,另一种则是将文档作为注释附加到PDF的页面中。

1.1  将文档作为文件附件添加到PDF

该方法是通过调用PdfAttachmentCollection类的Add()方法将文档添加到PdfDocument对象的Attachments集合中。

//加载PDF文档
PdfDocument pdf = new PdfDocument("Test.pdf");

//加载需要附加的文档
PdfAttachment attachment = new PdfAttachment("New.pdf");
//将文档添加到原PDF文档的附件集合中
pdf.Attachments.Add(attachment);

//保存文档
pdf.SaveToFile("Attachment1.pdf");

                      

1.2  将文档作为注释(annotation)附加到PDF文档的页面

创建注释时,我们需要用到以下类PdfAttachmentAnnotation:

namespace Spire.Pdf.Annotations
{
    // Summary:
    //     Represents an attachment annotation.
    public class PdfAttachmentAnnotation : PdfFileAnnotation
    {
        //
        // Parameters:
        //   rectangle:
        //     Bounds of the annotation.
        //
        //   fileName:
        //     A string value specifying the full path to the file to be embedded in the
        //     PDF file.
        public PdfAttachmentAnnotation(RectangleF rectangle, string fileName);
        //
        //
        // Parameters:
        //   rectangle:
        //     Bounds of the annotation.
        //
        //   fileName:
        //     A string value specifying the full path to the file to be embedded in the
        //     PDF file.
        //
        //   data:
        //     A byte array specifying the content of the annotation's embedded file.
        //
        // Remarks:
        //     If both FileName and FileContent are specified, the FileContent takes precedence.
        public PdfAttachmentAnnotation(RectangleF rectangle, string fileName, byte[] data);
        //
        //
        // Parameters:
        //   rectangle:
        //     The rectangle.
        //
        //   fileName:
        //     A string value specifying the full path to the file to be embedded in the
        //     PDF file.
        //
        //   stream:
        //     The stream specifying the content of the annotation's embedded file.
        //
        // Remarks:
        //     If both FileName and FileContent are specified, the FileContent takes precedence.
        public PdfAttachmentAnnotation(RectangleF rectangle, string fileName, Stream stream);

        public override string FileName { get; set; }
        //
        // Summary:
        //     Gets or Sets attachment's icon.
        public PdfAttachmentIcon Icon { get; set; }

        protected override void Initialize();
        protected override void Save();
    }
}

 代码段:

//加载PDF文档
PdfDocument doc = new PdfDocument("Test.pdf");

//给文档添加一个新页面
PdfPageBase page = doc.Pages.Add();

//添加文本到页面
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, System.Drawing.FontStyle.Bold));
page.Canvas.DrawString("Attachments:", font1, PdfBrushes.CornflowerBlue, new Point(50, 50));

//将文档作为注释添加到页面
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, System.Drawing.FontStyle.Bold));
PointF location = new PointF(52, 80);
String label = "Report.docx";
byte[] data = File.ReadAllBytes("Report.docx");
SizeF size = font2.MeasureString(label);
RectangleF bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.MediumPurple, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation1 = new PdfAttachmentAnnotation(bounds, "Report.docx", data);
annotation1.Color = Color.Purple;
annotation1.Flags = PdfAnnotationFlags.NoZoom;
annotation1.Icon = PdfAttachmentIcon.Graph;
annotation1.Text = "Report.docx";
(page as PdfNewPage).Annotations.Add(annotation1);

//保存文档
doc.SaveToFile("Attachment2.pdf");


 

2.  获取附件

根据附件添加方式的不同,获取附件也分为以下两种相应的方式。

2.1  获取文件附件

获取文件附件时,我们还可以获取附件的信息如文件名,MimeType,描述,创建日期和修改日期等。

//加载PDF文档
PdfDocument pdf = new PdfDocument("Attachment1.pdf");

//获取文档的第一个文件附件
PdfAttachment attachment = pdf.Attachments[0];

//获取该附件的信息
Console.WriteLine("Name: {0}", attachment.FileName);
Console.WriteLine("MimeType: {0}", attachment.MimeType);
Console.WriteLine("Description: {0}", attachment.Description);
Console.WriteLine("Creation Date: {0}", attachment.CreationDate);
Console.WriteLine("Modification Date: {0}", attachment.ModificationDate);

//将附件的数据写入到新文档
File.WriteAllBytes(attachment.FileName, attachment.Data);
Console.ReadKey();

 

2.2  获取注释附件

//加载PDF文档
PdfDocument pdf = new PdfDocument("Attachment2.pdf");

//实例化一个list并将文档内所有页面的Attachment annotations添加到该list
List<PdfAttachmentAnnotationWidget> attaches = new List<PdfAttachmentAnnotationWidget>();
foreach (PdfPageBase page in pdf.Pages)
{
    foreach (PdfAnnotation annotation in page.AnnotationsWidget)
    {
        attaches.Add(annotation as PdfAttachmentAnnotationWidget);
    }
}

//遍历list,将附件数据写入到新文档
for (int i = 0; i < attaches.Count; i++)
{
    File.WriteAllBytes(attaches[i].FileName, attaches[i].Data);
}

 

3.  删除附件

3.1  删除文件附件

//加载PDF文档
PdfDocument pdf = new PdfDocument("Attachment1.pdf");

//删除文档的所有文件附件
for (int i = 0; i < pdf.Attachments.Count; i++)
{
    pdf.Attachments.RemoveAt(i);
} 

//保存文档
pdf.SaveToFile("Remove.pdf");

 

3.2  删除注释附件

//加载PDF文档
PdfDocument pdf = new PdfDocument("Attachment2.pdf");

//删除文档的所有注释附件
foreach (PdfPageBase page in pdf.Pages)
{
    for (int i = 0; i < page.AnnotationsWidget.Count; i++)
    {
        PdfAnnotation annotation = page.AnnotationsWidget[i] as PdfAttachmentAnnotationWidget;

        page.AnnotationsWidget.Remove(annotation);                   
    }
}

//保存文档
pdf.SaveToFile("Result.pdf");

 

总结:

本文只对该dll的部分功能做了简单的介绍,如果需要了解更多内容,可以去官网或NuGet下载dll进行测试。

相关文章:

  • HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的原理和区别
  • Flask 5 模板1
  • hibernate主键为字符串的注解
  • spring拦截器
  • C#实现正则表达式
  • mitmproxy
  • tableView选择多项或单选
  • ip_conntrack table full dropping packet解决方案
  • Oracle for 循环
  • c++免注册大漠插件
  • 求上限值的整数勾股数
  • 微信小程序把玩(二十二)action-sheet组件
  • Python爬虫入门六之Cookie的使用
  • mysql学习笔记(二)--- MySQL数据类型
  • 【转】 android中的文件操作详解以及内部存储和外部存储
  • SegmentFault for Android 3.0 发布
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • Angularjs之国际化
  • HomeBrew常规使用教程
  • Java小白进阶笔记(3)-初级面向对象
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • linux学习笔记
  • Python_OOP
  • Quartz实现数据同步 | 从0开始构建SpringCloud微服务(3)
  • vue2.0项目引入element-ui
  • vue-loader 源码解析系列之 selector
  • 发布国内首个无服务器容器服务,运维效率从未如此高效
  • 高度不固定时垂直居中
  • 类orAPI - 收藏集 - 掘金
  • 前端面试总结(at, md)
  • 区块链分支循环
  • 试着探索高并发下的系统架构面貌
  • 适配mpvue平台的的微信小程序日历组件mpvue-calendar
  • Redis4.x新特性 -- 萌萌的MEMORY DOCTOR
  • ​3ds Max插件CG MAGIC图形板块为您提升线条效率!
  • (aiohttp-asyncio-FFmpeg-Docker-SRS)实现异步摄像头转码服务器
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • .form文件_一篇文章学会文件上传
  • .locked1、locked勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET CF命令行调试器MDbg入门(三) 进程控制
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .NET Core 中插件式开发实现
  • .NET Core实战项目之CMS 第十二章 开发篇-Dapper封装CURD及仓储代码生成器实现
  • .NET WebClient 类下载部分文件会错误?可能是解压缩的锅
  • .NET 设计模式初探
  • .net/c# memcached 获取所有缓存键(keys)
  • .NET/C# 获取一个正在运行的进程的命令行参数
  • .NET6 命令行启动及发布单个Exe文件
  • [DevEpxress]GridControl 显示Gif动画
  • [FC][常见Mapper IRQ研究]
  • [flume$2]记录一个写自定义Flume拦截器遇到的错误
  • [GN] Vue3快速上手1
  • [JavaEE系列] Thread类的基本用法