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. java 自动备份MySQL 数据库(转载)

    1 package com.learn4j.bat; public class Backup { private String user_name;// 数据库用户名 private String u ...

  2. vs生成解决方案错误无法将文件“xx.*”复制到xx.*”。对路径“bin\xx.*”的访问被拒绝

    使用vs2008生成解决方案时出现的问题: 无法将文件“obj\xx.*”复制到“bin\xx.*”.对路径“bin\xx.*”的访问被拒绝 解决方法: 将*.dll的只读属性去掉(在windows对 ...

  3. 学习c++语言应该牢记的50条准则,同样学习其他语言也一样

    1.把C++当成一门新的语言学习(和C没啥关系!真的.): 2.看<Thinking In C++>,不要看<C++变成死相>: 3.看<The C++ Programm ...

  4. NSCalendar 日历类

    NSCalendar 日历类 Cocoa中对日期和时间的处理 NSCalendar (一) (2008-11-12 21:54:10) NSCalendar用于处理时间相关问题.比如比较时间前后.计算 ...

  5. jQuery EasyUI学习资源汇总

    jQuery EasyUI学习资源汇总 EasyUi – 1.入门 EasyUi – 2.布局Layout + 3.登录界面 EasyUi – 4.datwagrid 学习Jquery EasyUI的 ...

  6. OD提示 "为了执行系统不支持的动作, OllyICE 在这个被调试的程序中注入了一点代码, 但是经过5秒仍未收到响应..." 解决办法

    别的OD就可以,我自己整合过的一个很顺手的OD就是不行,最后找到了解决办法: 转自:http://bbs.pediy.com/showthread.PHP?t=97629 -------------- ...

  7. JMeter 连接数据库报错No suitable driver found for jdbc:xxxxxxxxx

    添加JDBC Connection Configuration 和 JDBC Request 组件,添加相关信息 注意两个组件里面输入的Variable Name 必须一致 运行查看结果树出现如下错误 ...

  8. WebStorm界面出现中文乱码(出现口口口)

    不少刚刚使用WebStorm软件的童鞋,发现在新建一个项目时,如果输入中文,会显示成口口口.这个问题要怎么解决呢... 点一下界面上那个扳手图标(settings),快捷键Ctrl+Alt+S. 2 ...

  9. doubango(1)--从协议栈结构说起

    自顶向下与自底向上 软件设计的两种方法不过于自顶向下与自底向上. 对于自顶向下而言,先设计好用户接口,再往下延伸至各个功能块的具体实现.而对于自底向上而言,自然是有了设计好的各个功能代码块,再将这些功 ...

  10. HttpServletRequest和ServletRequest的区别

    servlet理论上可以处理多种形式的请求响应形式,http只是其中之一所以HttpServletRequest HttpServletResponse分别是ServletRequest和Servle ...