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進行測試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM