1 package org.simantics.export.core.pdf;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.util.ArrayList;
9 import com.lowagie.text.pdf.PRStream;
10 import com.lowagie.text.pdf.PdfArray;
11 import com.lowagie.text.pdf.PdfDictionary;
12 import com.lowagie.text.pdf.PdfName;
13 import com.lowagie.text.pdf.PdfReader;
14 import com.lowagie.text.pdf.PdfString;
16 public class ImportPdfReader {
18 /** File if opened from file */
21 /** iText pdf reader */
22 public PdfReader reader;
24 List<Attachment> attachments;
26 public ImportPdfReader() {
29 public ImportPdfReader(File file) throws IOException {
31 reader = new PdfReader(file.getAbsolutePath());
34 public List<Attachment> getAttachments() {
35 if ( attachments != null ) return attachments;
36 attachments = new ArrayList<Attachment>();
37 PdfDictionary root = reader.getCatalog();
38 PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(root.get(PdfName.NAMES));
41 PdfDictionary embeddedfiles = names.getAsDict(PdfName.EMBEDDEDFILES);
42 if (embeddedfiles == null)
44 PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES);
45 if (filespecs == null)
47 for (int i = 0; i < filespecs.size();) {
48 Attachment a = new Attachment();
49 filespecs.getAsString(i++);
50 a.filespec = filespecs.getAsDict(i++);
51 a.refs = a.filespec.getAsDict(PdfName.EF);
52 for (Object _key : a.refs.getKeys()) {
53 a.key = (PdfName) _key;
54 a.filename = a.filespec.getAsString(a.key);
61 public List<Attachment> getAttachments(String extension) {
62 ArrayList<Attachment> result = new ArrayList<Attachment>();
63 for ( Attachment a : getAttachments() ) {
64 if ( a.getFilename().endsWith(extension) ) {
78 public static class Attachment {
79 PdfDictionary filespec;
84 public String getFilename() {
85 return filename.toUnicodeString();
88 public void saveTo(File file) throws IOException {
91 if ( !file.exists() ) file.createNewFile();
92 fos = new FileOutputStream(file);
94 stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key));
95 fos.write(PdfReader.getStreamBytes(stream));