/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.pdmodel;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Map;

import org.apache.pdfbox.exceptions.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;

/**
 * This is an example on how to extract all embedded files from a PDF document.
 * <p>
 * Usage: java org.apache.pdfbox.examples.pdmodel.ExtractEmbeddedFiles &lt;input-pdf&gt;
 *
 * @version $Revision$
 */
public class ExtractEmbeddedFiles
{
    private ExtractEmbeddedFiles()
    {
    }

    /**
     * This is the main method.
     *
     * @param args The command line arguments.
     *
     * @throws Exception If there is an error parsing the document.
     */
    public static void main( String[] args ) throws Exception
    {
        if( args.length != 1 )
        {
            usage();
            System.exit(1);
        }
        else
        {
            PDDocument document = null;

            try
            {
                File pdfFile = new File(args[0]);
                String filePath = pdfFile.getParent() + System.getProperty("file.separator");
                document = PDDocument.load( pdfFile );
                if (document.isEncrypted()) 
                {
                    try
                    {
                        document.decrypt("");
                    }
                    catch( InvalidPasswordException e )
                    {
                        System.err.println( "Error: The document is encrypted." );
                    }
                    catch( org.apache.pdfbox.exceptions.CryptographyException e )
                    {
                        e.printStackTrace();
                    }
                }
                PDDocumentNameDictionary namesDictionary = 
                    new PDDocumentNameDictionary( document.getDocumentCatalog() );
                PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles();
                if (efTree != null)
                {
                    Map<String,Object> names = efTree.getNames();
                    Iterator<String> namesKeys = names.keySet().iterator();
                    while (namesKeys.hasNext())
                    {
                        String filename = namesKeys.next();
                        PDComplexFileSpecification fileSpec = (PDComplexFileSpecification)names.get(filename);
                        PDEmbeddedFile embeddedFile = fileSpec.getEmbeddedFile();
                        String embeddedFilename = filePath+filename;
                        File file = new File(filePath+filename);
                        System.out.println("Writing "+ embeddedFilename);
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(embeddedFile.getByteArray());
                        fos.close();
                    }
                }
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }


    /**
     * This will print the usage for this program.
     */
    private static void usage()
    {
        System.err.println( "Usage: java " + ExtractEmbeddedFiles.class.getName() + " <input-pdf>" );
    }
}

@@ -911,21 +911,45 @@
 ava.
-util.Iterator
+io.IOException;%0Aimport java.util.List
 ;%0Aim
@@ -1197,16 +1197,127 @@
 eeNode;%0A
+import org.apache.pdfbox.pdmodel.common.COSObjectable;%0Aimport org.apache.pdfbox.pdmodel.common.PDNameTreeNode;%0A
 import o
@@ -2171,17 +2171,16 @@
 = null;%0A
-%0A
         
@@ -3029,16 +3029,20 @@
         
+    
 new PDDo
@@ -3270,22 +3270,29 @@
 %3CString,
+COS
 Object
+able
 %3E names 
@@ -3336,60 +3336,375 @@
     
-Iterator%3CString%3E namesKeys = names.keySet().iterator
+if (names != null)%0A                    %7B%0A                        extractFiles(names, filePath);%0A                    %7D%0A                    else%0A                    %7B%0A                        List%3CPDNameTreeNode%3E kids = efTree.getKids();%0A                        for (PDNameTreeNode node : kids)%0A                        %7B%0A                            names = node.getNames
 ();%0A
@@ -3727,82 +3727,444 @@
     
-while 
+        extractFiles
 (names
-Keys.hasNext())%0A                    %7B%0A             
+, filePath);%0A                        %7D%0A                    %7D%0A                %7D%0A            %7D%0A            finally%0A            %7B%0A                if( document != null )%0A                %7B%0A                    document.close();%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A%0A    private static void extractFiles(Map%3CString,COSObjectable%3E names, String filePath) %0A            throws IOException%0A
     
+%7B%0A
        
+ for (
 Stri
@@ -4179,27 +4179,25 @@
 ame 
-=
+:
  names
-Keys.next();
+.keySet())
 %0A   
@@ -4193,35 +4193,34 @@
 ySet())%0A        
-   
+%7B%0A
              PDC
@@ -4215,17 +4215,16 @@
         
- 
 PDComple
@@ -4298,36 +4298,24 @@
 (filename);%0A
-            
             
@@ -4380,36 +4380,24 @@
             
-            
 String embed
@@ -4437,36 +4437,24 @@
             
-            
 File file = 
@@ -4478,36 +4478,24 @@
 +filename);%0A
-            
             
@@ -4552,36 +4552,24 @@
             
-            
 FileOutputSt
@@ -4615,36 +4615,24 @@
             
-            
 fos.write(em
@@ -4671,28 +4671,16 @@
         
-            
 fos.clos
@@ -4696,232 +4696,15 @@
     
-            %7D%0A                %7D%0A            %7D%0A            finally%0A            %7B%0A                if( document != null )%0A                %7B%0A                    document.close();%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A
+%7D%0A    %7D
 %0A   

handle both kinds of embedded files tree configurations