How to add, get, delete PDF attachments in C#/VB.NET

Overview

Attachments refer to the relevant documents or items issued with the documents. In PDF documents, we can add documents of the same type or other types as attachment content, and attachments in PDF can also be divided into two forms, one is that the attachment exists in the form of a normal file, and the other is an annotation. form exists. How to add the above two forms of PDF attachments is described in the following example. In addition, according to the different ways of adding PDF attachments, when we obtain PDF attachment information or delete PDF attachments, we can also perform operations according to circumstances.

gist index

1. Add PDF attachments1.1 Add attachments
as normal documents1.2 Add attachments
as document comments2
. Get PDF attachments2.1
Get file attachments2.2
Get annotation attachments3
. Delete PDF attachments3.1
Delete file attachments3.2
Delete annotation attachments

tool usage

Spire.PDF for .NET 4.0

Example operation

1. Add PDF attachments

1.1 Add attachments as normal documents

C

using Spire.Pdf;
using Spire.Pdf.Attachments;

namespace AddAttachment_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个PdfDocument类对象,加载测试文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("sample.pdf");

            //初始化PdfAttachment类实例,加载需要附加的文档
            PdfAttachment attachment = new PdfAttachment("New.pdf");

            //将文档添加到原PDF文档的附件集合中
            pdf.Attachments.Add(attachment);

            //保存并打开文档
            pdf.SaveToFile("Attachment1.pdf");
            System.Diagnostics.Process.Start("Attachment1.pdf");
        }
    }
}

Test Results:
How to add, get, delete PDF attachments in C#/VB.NET

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Attachments

Namespace AddAttachment_PDF

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim pdf As PdfDocument = New PdfDocument()
            pdf.LoadFromFile("sample.pdf")
            Dim attachment As PdfAttachment = New PdfAttachment("New.pdf")
            pdf.Attachments.Add(attachment)
            pdf.SaveToFile("Attachment1.pdf")
            System.Diagnostics.Process.Start("Attachment1.pdf")
        End Sub
    End Class
End Namespace

1.2 Add attachments as documentation comments

Csharp

using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
using System.IO;

namespace AddAttachment2
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个PdfDocument类对象,加载测试文档
            PdfDocument doc = new PdfDocument("sample.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 = "sample.docx";
            byte[] data = File.ReadAllBytes("sample.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, "sample.docx", data);
            annotation1.Color = Color.Purple;
            annotation1.Flags = PdfAnnotationFlags.NoZoom;
            annotation1.Icon = PdfAttachmentIcon.Graph;
            annotation1.Text = "sample.docx";
            (page as PdfNewPage).Annotations.Add(annotation1);

            //保存并打开文档
            doc.SaveToFile("Attachment2.pdf");
            System.Diagnostics.Process.Start("Attachment2.pdf");
        }
    }
}

Test Results:
How to add, get, delete PDF attachments in C#/VB.NET

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.Graphics
Imports System
Imports System.Drawing
Imports System.IO

Namespace AddAttachment2

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim doc As PdfDocument = New PdfDocument("sample.pdf")
            Dim page As PdfPageBase = doc.Pages.Add()
            Dim font1 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 16F, System.Drawing.FontStyle.Bold))
            page.Canvas.DrawString("Attachments:", font1, PdfBrushes.CornflowerBlue, New Point(50, 50))
            Dim font2 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 12F, System.Drawing.FontStyle.Bold))
            Dim location As PointF = New PointF(52, 80)
            Dim label As String = "sample.docx"
            Dim data As Byte() = File.ReadAllBytes("sample.docx")
            Dim size As SizeF = font2.MeasureString(label)
            Dim bounds As RectangleF = 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)
            Dim annotation1 As PdfAttachmentAnnotation = New PdfAttachmentAnnotation(bounds, "sample.docx", data)
            annotation1.Color = Color.Purple
            annotation1.Flags = PdfAnnotationFlags.NoZoom
            annotation1.Icon = PdfAttachmentIcon.Graph
            annotation1.Text = "sample.docx"
            (TryCast(page, PdfNewPage)).Annotations.Add(annotation1)
            doc.SaveToFile("Attachment2.pdf")
            System.Diagnostics.Process.Start("Attachment2.pdf")
        End Sub
    End Class
End Namespace

2. Get PDF attachments

2.1 Get file attachments

Csharp

using Spire.Pdf;
using Spire.Pdf.Attachments;
using System;
using System.IO;

namespace GetAttachment_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建PDF文档,加载测试文件
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("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();
        }
    }
}

Test Results:
How to add, get, delete PDF attachments in C#/VB.NET

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Attachments
Imports System
Imports System.IO

Namespace GetAttachment_PDF

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim pdf As PdfDocument = New PdfDocument()
            pdf.LoadFromFile("Attachment1.pdf")
            Dim attachment As PdfAttachment = 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()
        End Sub
    End Class
End Namespace

2.2 Get annotation attachments

Csharp

using Spire.Pdf;
using Spire.Pdf.Annotations;
using System.Collections.Generic;
using System.IO;

namespace GetAttachment2
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("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);
            }

        }
    }
}

Test Results:
How to add, get, delete PDF attachments in C#/VB.NET

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports System.Collections.Generic
Imports System.IO

Namespace GetAttachment2

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim pdf As PdfDocument = New PdfDocument()
            pdf.LoadFromFile("Attachment2.pdf")
            Dim attaches As List(Of PdfAttachmentAnnotationWidget) = New List(Of PdfAttachmentAnnotationWidget)()
            For Each page As PdfPageBase In pdf.Pages
                For Each annotation As PdfAnnotation In page.AnnotationsWidget
                    attaches.Add(TryCast(annotation, PdfAttachmentAnnotationWidget))
                Next
            Next

            For i As Integer = 0 To attaches.Count - 1
                File.WriteAllBytes(attaches(i).FileName, attaches(i).Data)
            Next
        End Sub
    End Class
End Namespace

3. Delete PDF attachments

3.1 Deleting file attachments

Csharp

using Spire.Pdf;

namespace DeleteAttachment_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Attachment1.pdf");

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

            //保存并打开文档
            pdf.SaveToFile("Remove.pdf");
            System.Diagnostics.Process.Start("Remove.pdf");

        }
    }
}

VB.NET

Imports Spire.Pdf

Namespace DeleteAttachment_PDF

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim pdf As PdfDocument = New PdfDocument()
            pdf.LoadFromFile("Attachment1.pdf")
            For i As Integer = 0 To pdf.Attachments.Count - 1
                pdf.Attachments.RemoveAt(i)
            Next

            pdf.SaveToFile("Remove.pdf")
            System.Diagnostics.Process.Start("Remove.pdf")
        End Sub
    End Class
End Namespace

3.2 Delete annotation attachment

Csharp

using Spire.Pdf;
using Spire.Pdf.Annotations;

namespace DeleteAttachment2
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("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");
            System.Diagnostics.Process.Start("Result.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Annotations

Namespace DeleteAttachment2

    Class Program

        Private Shared Sub Main(ByVal args As String())
            Dim pdf As PdfDocument = New PdfDocument()
            pdf.LoadFromFile("Attachment2.pdf")
            For Each page As PdfPageBase In pdf.Pages
                For i As Integer = 0 To page.AnnotationsWidget.Count - 1
                    Dim annotation As PdfAnnotation = TryCast(page.AnnotationsWidget(i), PdfAttachmentAnnotationWidget)
                    page.AnnotationsWidget.Remove(annotation)
                Next
            Next

            pdf.SaveToFile("Result.pdf")
            System.Diagnostics.Process.Start("Result.pdf")
        End Sub
    End Class
End Namespace

After debugging the program, the generated document has no attachments.

All the above content is described in this time about the method of "C#/VB.NT Operation PDF Attachment". The code is for reference, I hope it can provide you with some ideas to solve the problem.

(If you want to reprint this article, please indicate the source.)

Thanks for reading!

"End of this article"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324753015&siteId=291194637
Recommended