import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
public class PDFAttachments {
public PDFAttachments() {
}
public void extractAttachments(String src, String dest) throws IOException {
PdfReader reader = new PdfReader(src);
PdfArray array;
PdfDictionary annot;
PdfDictionary fs;
PdfDictionary refs;
String fName;
try {
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
array = reader.getPageN(i).getAsArray(PdfName.ANNOTS);
if (array == null)
continue;
for (int j = 0; j < array.size(); j++) {
annot = array.getAsDict(j);
if (PdfName.FILEATTACHMENT.equals(annot
.getAsName(PdfName.SUBTYPE))) {
fs = annot.getAsDict(PdfName.FS);
refs = fs.getAsDict(PdfName.EF);
for (PdfName name : refs.getKeys()) {
fName = dest + fs.getAsString(name).toString();
/*
* FileOutputStream fos = new
* FileOutputStream(String.format(dest,
* fs.getAsString(name).toString()));
*/
FileOutputStream fos = new FileOutputStream(fName);
fos.write(PdfReader.getStreamBytes((PRStream) refs
.getAsStream(name)));
fos.flush();
fos.close();
}
}
}
}
} catch (Exception e) {
System.err.println("exception " + e.getMessage());
}
}
}
}