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(, )); //将文档作为注释添加到页面
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, System.Drawing.FontStyle.Bold));
PointF location = new PointF(, );
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 + , bounds.Top, font2.Height / , 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[]; //获取该附件的信息
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 = ; 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 = ; 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 = ; i < page.AnnotationsWidget.Count; i++)
{
PdfAnnotation annotation = page.AnnotationsWidget[i] as PdfAttachmentAnnotationWidget; page.AnnotationsWidget.Remove(annotation);
}
} //保存文档
pdf.SaveToFile("Result.pdf");

总结:

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

C# 添加、获取及删除PDF附件的更多相关文章

  1. C# 添加、修改和删除PDF书签

    C# 添加.修改和删除PDF书签 有时候我们在阅读PDF文档时会遇到这样一种情况:PDF文档页数比较多,但是又没有书签,所以我们不能根据书签快速了解文档所讲解的内容,也不能点击书签快速跳转到相应的位置 ...

  2. Java添加、提取、替换和删除PDF图片

    (一)简介 这篇文章将介绍在Java中添加.提取.删除和替换PDF文档中的图片. 工具使用: Free Spire.PDF for JAVA 2.4.4(免费版) Intellij IDEA Jar包 ...

  3. JAVA 添加、修改和删除PDF书签

    当阅读篇幅较长的PDF文档时,为方便我们再次阅读时快速定位到上一次的阅读位置,可以插入一个书签进行标记:此外,对于文档中已有的书签,我们也可以根据需要进行修改或者删除等操作.本篇文章将通过Java编程 ...

  4. Java 添加、替换、删除PDF中的图片

    概述 本文介绍通过java程序向PDF文档添加图片,以及替换和删除PDF中已有的图片.另外,关于图片的操作还可参考设置PDF 图片背景.设置PDF图片水印.读取PDF中的图片.将PDF保存为图片等文章 ...

  5. 工具函数:cookie的添加、获取、删除

    cookie是浏览器存储的命名数据,作用是保存用户的信息,这样我们就可以用这些信息来做一些事了,但是cookie容量很小,只有4kb. 下面是我总结的cookie的添加.获取.删除的函数: cooki ...

  6. Java 添加、隐藏/显示、删除PDF图层

    本文介绍操作PDF图层的方法.可分为添加图层(包括添加线条.形状.字符串.图片等图层).隐藏或显示图层.删除图层等.具体可参考如下Java代码示例. 工具:Free Spire.PDF for Jav ...

  7. 利用jquery给指定的table动态添加一行、删除一行

    转自:http://www.cnblogs.com/linjiqin/p/3148181.html $("#mytable tr").find("td:nth-child ...

  8. 利用jquery给指定的table动态添加一行、删除一行,复制,值不重复等操作

    $("#mytable tr").find("td:nth-child(1)") 1表示获取每行的第一列$("#mytable tr").f ...

  9. iOS UIWebView 和 WKWebView 的 cookie 获取,设置,删除

    Cookie简介说到Cookie,或许有些小伙伴会比较陌生,有些小伙伴会比较熟悉.如果项目中,所有页面都是纯原生来实现的话,一般Cookie这个东西或许我们永远也不会接触到.但是,这里还是要说一下Co ...

随机推荐

  1. s3c2440的GPIO驱动

    多个通用的GPIO,同时这些端口也拥有一些复用功能(如ADC输入),有部分端口只能输入,有部分端口只能输出,今天我们来看看如何设置一个GPIO的输出电平以及如何获取一个端口的GPIO电平 对GPIO进 ...

  2. awk程序设计语言之-awk基础

    awk程序设计语言之-awk基础 http://man.linuxde.net/ 常用工具命令之awk命令 awk是一种编程语言,用于在Linux/Unix下对文本和数据处理.数据可以来自标准输入(s ...

  3. iOS 消息推送原理及实现总结 分类: ios技术 2015-03-01 09:22 70人阅读 评论(0) 收藏

    在实现消息推送之前先提及几个于推送相关概念,如下图: 1. Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Provider可以理解为服 ...

  4. imagebutton、imageview的属性

    [转]http://blog.csdn.net/victoryckl/article/details/14162131 http://blog.sina.com.cn/s/blog_68b3fdc30 ...

  5. adapter中报错:Can't create handler inside thread that has not called Looper.prepare()

    http://stackoverflow.com/questions/9357513/cant-create-handler-inside-thread-that-has-not-called-loo ...

  6. shell 整理,更新,记录

    菜鸟级awk,读取android manifest,把key->value 保存到path.rc. awk -F "name=" '{if(/project path/) p ...

  7. 【腾讯优测干货分享】微信小程序之自动化亲密接触

    本文来自于腾讯优测公众号(wxutest),未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/HcPakz5CV1SHnu-U8n85pw 导语 山雨欲来风满楼,最 ...

  8. jquery proxy

    slice = Array.prototype.slice,// Bind a function to a context, optionally partially applying any // ...

  9. codeforces 755D. PolandBall and Polygon

    D. PolandBall and Polygon time limit per test 4 seconds memory limit per test 256 megabytes input st ...

  10. sqlite3编译

    1.sqlite3编译: 1.PC版: 1.解压: tar xvf sqlite-autoconf-3140100.tar.gz cd sqlite-autoconf-3140100/ 2.检查配置 ...