Foxit PDF SDK for Android

How to Add Attachments to PDFs with Foxit PDF SDK for Android

With Foxit PDF SDK, attachments refers to attachments of documents rather than file attachment annotations, which allow whole files to be embedded in a document, much like email attachments. PDF SDK provides application APIs to access attachments such as loading attachments, getting attachments, inserting/removing attachments, and accessing properties of attachments.

Example:

How to embed a specified file to a PDF document

import com.foxit.sdk.PDFException;
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.common.Constants;
import com.foxit.sdk.pdf.Attachments;
import com.foxit.sdk.pdf.FileSpec;
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.sdk.pdf.objects.PDFNameTree;
...
try {
 String pdfpath = "XXX/Sample.pdf";
 PDFDoc doc = new PDFDoc(pdfpath);
 // Embed the specified file to PDF document.
 String filePath = "/xxx/fileToBeEmbedded.xxx";
 PDFNameTree nameTree = new PDFNameTree(doc, PDFNameTree.e_EmbeddedFiles);
 Attachments attachments = new Attachments(doc, nameTree);
 FileSpec fileSpec = new FileSpec(doc);
 fileSpec.setFileName(filePath);
 if (!fileSpec.embed(filePath)) return;
 attachments.addEmbeddedFile(filePath, fileSpec);
} catch (PDFException e) {
 e.printStackTrace();
}
...

How to export the embedded attachment file from a PDF and save it as a single file

import com.foxit.sdk.PDFException;
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.common.Constants;
import com.foxit.sdk.pdf.Attachments;
import com.foxit.sdk.pdf.FileSpec;
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.sdk.pdf.objects.PDFNameTree;
...
try {
 String pdfpath = "XXX/Sample.pdf";
 PDFDoc doc = new PDFDoc(pdfpath);
 PDFNameTree nameTree = new PDFNameTree(doc, PDFNameTree.e_EmbeddedFiles);
 Attachments attachments = new Attachments(doc, nameTree);
 // Extract the embedded attachment file.
 int count = attachments.getCount();
 for (int i = 0; i < count; i ++) {
 String key = attachments.getKey(i);
 if (key != null) {
 FileSpec fileSpec1 = attachments.getEmbeddedFile(key);
 String exportedFile = "/somewhere/" + fileSpec1.getFileName();
 if (fileSpec1 != null && !fileSpec1.isEmpty()) {
 fileSpec1.exportToFile(exportedFile);
 }
 }
 }
} catch (PDFException e) {
 e.printStackTrace();
}
...

Updated on June 7, 2019

Was this article helpful?
Thanks for your feedback. If you have a comment on how to improve the article, you can write it here: