Working with attachments in pdf using c#

Dheeraj1987
Posted by in .NET Framework category on for Beginner level | Points: 250 | Views : 819 red flag

In this article we will explain how to work with attachments in pdf using c#. Such as add attachments to pdf, create a GoToE action to a pdf attachment, get the information of an attachment and save it to file, delete attachment from pdf.

Introduction 

An attachment is an additional file that is attached to a parent document, it can be a variety of file types, such as pdf, word, image or other files. In this article we will explain how to work with these attachments in pdf programmatically with c#.

Contents summary:

  •        Add attachments to pdf
  •        Create a GoToE action to a pdf attachment
  •         Get the information of an attachment and save it to file
  •         Delete attachment from pdf

Prerequisite

To acheive these tasks, we used a pdf library which can be easily downloaded from nuget by using this line of code:

PM> Install-Package Spire.PDF

Using the code

Add attachments to pdf

The library provides an easy way to add attachments to a pdf document by calling thePdfAttachmentCollection.Add(PdfAttachment attachment) method, but here we're introducing another way to add attachments by creating attachment annotations.

//Load the original pdf document.
PdfDocument doc = new PdfDocument("Sales.pdf");
//Add a new page
PdfPageBase page = doc.Pages.Add();
 
float y = 10;
//Set title text
PdfBrush brush1 = PdfBrushes.CornflowerBlue;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, System.Drawing.FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Attachments", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Attachments", format1).Height;
y = y + 5;
 
//Attach a word document
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, System.Drawing.FontStyle.Bold));
PointF location = new PointF(50, y);
String label = "Sales Report";
byte[] data = File.ReadAllBytes("Sales 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, "Sales  Report.docx", data);
annotation1.Color = Color.Teal;
annotation1.Flags = PdfAnnotationFlags.NoZoom;
annotation1.Icon = PdfAttachmentIcon.Graph;
annotation1.Text = "Sales Report.docx";
(page as PdfNewPage).Annotations.Add(annotation1);
y = y + size.Height + 2;
 
//Attach an image
location = new PointF(50, y);
label = "Vendors Info";
data = File.ReadAllBytes("Vendors Info.png");
size = font2.MeasureString(label);
bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation2 = new PdfAttachmentAnnotation(bounds, "Vendors  Info.png", data);
annotation2.Color = Color.Orange;
annotation2.Flags = PdfAnnotationFlags.ReadOnly;
annotation2.Icon = PdfAttachmentIcon.PushPin;
annotation2.Text = "Vendors info image";
(page as PdfNewPage).Annotations.Add(annotation2);
 
//Save the document.
doc.SaveToFile("Attachment.pdf"); 

Screenshot:


Create a GoToE action to a pdf attachment

You can direct users to a pdf attachment by creating a GoToE action in the parent pdf document that jumps to the attachment.

//Create a pdf document and add a page to it.
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();
 
//Attach a pdf document to the newly created document.
PdfAttachment attachment = new PdfAttachment("New Zealand.pdf");
pdf.Attachments.Add(attachment);
 
//Add text to the page.
string text = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
float width = 490f;
float height = font.Height * 2.2f;
RectangleF rect = new RectangleF(0, 100, width, height);
page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);
 
//Create a GoToE action which allows jumping to the attached pdf document and open it in a new window at the 2nd page and 200% zoom factor.
PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);
PdfEmbeddedGoToAction action = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);
 
//Create an action annotation with the GoToE action and add it to the page’s annotation collection.
PdfActionAnnotation annotation = new PdfActionAnnotation(rect, action);
(page as PdfNewPage).Annotations.Add(annotation);
 
//Save the document.
pdf.SaveToFile("result.pdf");

Screenshot:


 

Get the information of an attachment and save it to file

//Load the parent pdf document.
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("result.pdf");
 
//Get the first attachment from the document’s attachment collection.
PdfAttachmentCollection attachments = pdf.Attachments;
PdfAttachment attachment = attachments[0];
 
//Print out the information of the attachment.
Console.WriteLine("Name: {0}", attachment.FileName);
Console.WriteLine("Description: {0}", attachment.Description);
Console.WriteLine("Creation Date: {0}", attachment.CreationDate);
Console.WriteLine("Modification Date: {0}", attachment.ModificationDate);
 
//Save the attachment to file.
File.WriteAllBytes(attachment.FileName, attachment.Data);

Screenshot:


 

Remove attachment from pdf

It’s possible to remove a specific attachment by name with this library, refer following code.

//Load the parent pdf document.
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("result.pdf");
//Get the document’s attachment collection.
PdfAttachmentCollection attachments = pdf.Attachments;
PdfAttachment attachment = null;
//Remove the specific attachment by name.
if (pdf.Attachments.Count > 0)
{
    foreach (PdfAttachment oneAttachment in pdf.Attachments)
    {
        string filename = oneAttachment.FileName;
        if (filename == "New Zealand.pdf")
        {
            attachment = oneAttachment;
            break;
        }
    }
}
if (attachment != null)
{
    pdf.Attachments.Remove(attachment);
}
//Save the document.
pdf.SaveToFile("Remove.pdf");
 Hope this article will help you a lot.


Page copy protected against web site content infringement by Copyscape

About the Author

Dheeraj1987
Full Name: Dheeraj Malik
Member Level: Starter
Member Status: Member
Member Since: 1/19/2017 10:21:44 PM
Country: India



Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)