Introduction
Embedded files, so-called pdf
attachments, are used to guarantee the validity of the document in case there
are external references in main content referring to them. For example, you can
include supplementary documentation or appendix as an embedded file and link to
it from some page of the main document. They can also be used in the same way
as email attachments, and pdf document will act as “envelope” containing
additional data. Using embedded files, PDF documents can be turned to
self-contained structured units.
Detailed description of this PDF
feature is contained in section 7.11.4
Embedded File Streams of the PDF specification.
Adding PDF attachments
Code sample below shows how to add attachments to PDF
document:
public void AddPDFAttachments()
{
//
create document
FixedDocument doc = new FixedDocument();
// add
attachments
doc.Attachments.Add("Appendix-A",new EmbeddedFile("appendix_a.txt"));
doc.Attachments.Add("Appendix-B",new EmbeddedFile("appendix_b.jpg"));
//
create text object
Page page = new Page();
TextObject textObject = new TextObject(StandardFonts.Helvetica,14);
textObject.AppendText("Document with attachments, created using Apitron PDF
Kit
for .NET");
page.Content.Translate(10,820);
page.Content.AppendText(textObject);
// add first
page
doc.Pages.Add(page);
// save
document
using (Stream stream = File.Create("pdf_attachments.pdf"))
{
doc.Save(stream);
}
}
Resulting image:
Pic. 1 Add pdf attachments
|
Note the panel on the left, with a paperclip, it allows you to view all attachments and open the desired file for viewing. You can also enumerate and read attachments programmatically, see the next sample.
Reading pdf attachments
See the code sample below that enumerates all attachments
and prints their names and sizes:
public void ReadPDFAttachments()
{
// open
document
using (Stream stream = File.Open("pdf_attachments.pdf",FileMode.Open))
{
FixedDocument doc = new FixedDocument(stream);
//
enumerate attachments, print their names and sizes
foreach (var fileEntry in doc.Attachments)
{
using (Stream attachmentStream = fileEntry.Value.GetStream())
{
Console.WriteLine("Found
attachment: {0}, Size: {1} bytes",
fileEntry.Key,attachmentStream.Length);
}
}
}
Console.ReadLine();
}
This code produces the following results:
You could also remove any attachment using the single call:
doc.Attachments.RemoveAttachment([attachment
key]);
Conclusion
Embedded files feature is very
useful for including additional data into the main PDF document without
changing its content. And as you could see from this article, managing
attachments is quite easy with fixed layout API offered by Apitron PDF Kit for .NET component.
This pdf manipulation library can be used to add, remove, enumerate, or read
any files attached to pdf documents. Contact us if you have any questions and
we’ll be happy to answer.
No comments:
Post a Comment