1 package it.stefanochizzolini.clown.samples; 2 3 import it.stefanochizzolini.clown.bytes.FileInputStream; 4 import it.stefanochizzolini.clown.bytes.IBuffer; 5 import it.stefanochizzolini.clown.objects.*; 6 import it.stefanochizzolini.clown.files.File; 7 import it.stefanochizzolini.clown.tokens.FileFormatException; 8 import java.io.RandomAccessFile ; 9 10 15 public class ImageExtractionSample 16 implements ISample 17 { 18 public void run( 19 PDFClownSampleLoader loader 20 ) 21 { 22 29 30 String filePath = loader.getPdfFileChoice("Please select a PDF file"); 32 33 FileInputStream inputStream; 35 try 36 { 37 inputStream = new FileInputStream( 39 new RandomAccessFile (filePath,"r") 40 ); 41 } 42 catch(Exception e) 43 {throw new RuntimeException (filePath + " file access error.",e);} 44 File file; 45 try 46 { 47 file = new File(inputStream); 49 } 50 catch(FileFormatException e) 51 {throw new RuntimeException (filePath + " file has a bad file format.",e);} 52 53 int index = 0; 55 for(PdfIndirectObject indirectObject : file.getIndirectObjects()) 56 { 57 PdfDataObject dataObject = indirectObject.getDataObject(); 59 if(dataObject instanceof PdfStream) 61 { 62 PdfDictionary header = ((PdfStream)dataObject).getHeader(); 63 if(header.containsKey(PdfName.Type) 65 && header.get(PdfName.Type).equals(PdfName.XObject) 66 && header.get(PdfName.Subtype).equals(PdfName.Image)) 67 { 68 if(header.get(PdfName.Filter).equals(PdfName.DCTDecode)) { 71 IBuffer body = ((PdfStream)dataObject).getBody(false); 73 exportImage( 75 body, 76 loader.getOutputPath() + java.io.File.separator + "ImageExtractionSample_" + (index++) + ".jpg" 77 ); 78 } 79 else { 81 System.out.println("Image XObject " + indirectObject.getReference() + " couldn't be extracted (filter: " + header.get(PdfName.Filter) + ")"); 82 } 83 } 84 } 85 } 86 } 87 88 private void exportImage( 89 IBuffer data, 90 String outputPath 91 ) 92 { 93 java.io.File outputFile = new java.io.File (outputPath); 94 java.io.BufferedOutputStream outputStream; 95 try 96 { 97 outputFile.createNewFile(); 98 outputStream = new java.io.BufferedOutputStream ( 99 new java.io.FileOutputStream (outputFile) 100 ); 101 } 102 catch(Exception e) 103 {throw new RuntimeException (outputFile.getPath() + " file couldn't be created.",e);} 104 105 try 106 { 107 outputStream.write(data.toByteArray()); 108 outputStream.flush(); 109 outputStream.close(); 110 } 111 catch(Exception e) 112 {throw new RuntimeException (outputFile.getPath() + " file writing has failed.",e);} 113 114 System.out.println("Output: " + outputFile.getPath()); 115 } 116 } | Popular Tags |