package org.simantics.export.core.pdf; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.lowagie.text.pdf.PRStream; import com.lowagie.text.pdf.PdfArray; import com.lowagie.text.pdf.PdfDictionary; import com.lowagie.text.pdf.PdfName; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfString; public class ImportPdfReader { /** File if opened from file */ public File file; /** iText pdf reader */ public PdfReader reader; List attachments; public ImportPdfReader() { } public ImportPdfReader(File file) throws IOException { this.file = file; reader = new PdfReader(file.getAbsolutePath()); } public List getAttachments() { if ( attachments != null ) return attachments; attachments = new ArrayList(); PdfDictionary root = reader.getCatalog(); PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(root.get(PdfName.NAMES)); if (names == null) return attachments; PdfDictionary embeddedfiles = names.getAsDict(PdfName.EMBEDDEDFILES); if (embeddedfiles == null) return attachments; PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES); if (filespecs == null) return attachments; for (int i = 0; i < filespecs.size();) { Attachment a = new Attachment(); filespecs.getAsString(i++); a.filespec = filespecs.getAsDict(i++); a.refs = a.filespec.getAsDict(PdfName.EF); for (Object _key : a.refs.getKeys()) { a.key = (PdfName) _key; a.filename = a.filespec.getAsString(a.key); attachments.add( a ); } } return attachments; } public List getAttachments(String extension) { ArrayList result = new ArrayList(); for ( Attachment a : getAttachments() ) { if ( a.getFilename().endsWith(extension) ) { result.add( a ); } } return result; } public void close() { if ( reader!=null ) { reader.close(); reader = null; } } public static class Attachment { PdfDictionary filespec; PdfDictionary refs; PdfName key; PdfString filename; public String getFilename() { return filename.toUnicodeString(); } public void saveTo(File file) throws IOException { FileOutputStream fos; PRStream stream; if ( !file.exists() ) file.createNewFile(); fos = new FileOutputStream(file); try { stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key)); fos.write(PdfReader.getStreamBytes(stream)); fos.flush(); } finally { fos.close(); } } } }