1 package org.simantics.export.core.pdf;
3 import java.io.Closeable;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.util.ArrayList;
10 import com.lowagie.text.pdf.PRStream;
11 import com.lowagie.text.pdf.PdfArray;
12 import com.lowagie.text.pdf.PdfDictionary;
13 import com.lowagie.text.pdf.PdfName;
14 import com.lowagie.text.pdf.PdfReader;
15 import com.lowagie.text.pdf.PdfString;
17 public class ImportPdfReader implements Closeable {
19 /** File if opened from file */
22 /** iText pdf reader */
23 public PdfReader reader;
25 List<Attachment> attachments;
27 public ImportPdfReader() {
30 public ImportPdfReader(File file) throws IOException {
32 reader = new PdfReader(file.getAbsolutePath());
35 public List<Attachment> getAttachments() {
36 if ( attachments != null ) return attachments;
37 attachments = new ArrayList<Attachment>();
38 PdfDictionary root = reader.getCatalog();
39 PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(root.get(PdfName.NAMES));
42 PdfDictionary embeddedfiles = names.getAsDict(PdfName.EMBEDDEDFILES);
43 if (embeddedfiles == null)
45 PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES);
46 if (filespecs == null)
48 for (int i = 0; i < filespecs.size();) {
49 Attachment a = new Attachment();
50 filespecs.getAsString(i++);
51 a.filespec = filespecs.getAsDict(i++);
52 a.refs = a.filespec.getAsDict(PdfName.EF);
53 for (Object _key : a.refs.getKeys()) {
54 a.key = (PdfName) _key;
55 a.filename = a.filespec.getAsString(a.key);
62 public List<Attachment> getAttachments(String extension) {
63 ArrayList<Attachment> result = new ArrayList<Attachment>();
64 for ( Attachment a : getAttachments() ) {
65 if ( a.getFilename().endsWith(extension) ) {
72 public synchronized void close() {
79 public static class Attachment {
80 PdfDictionary filespec;
85 public String getFilename() {
86 return filename.toUnicodeString();
89 public void saveTo(File file) throws IOException {
92 if ( !file.exists() ) file.createNewFile();
93 fos = new FileOutputStream(file);
95 stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key));
96 fos.write(PdfReader.getStreamBytes(stream));