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");
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuQjY4YzYjlTZyEGZ2ImMxUzN0EzNiNTZjhTY1U2Y2ETNfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
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進行測試。