1 31 package org.pdfbox.examples.fdf; 32 33 import java.io.IOException ; 34 35 import java.util.Iterator ; 36 import java.util.List ; 37 38 import org.pdfbox.pdmodel.interactive.form.PDAcroForm; 39 import org.pdfbox.pdmodel.interactive.form.PDField; 40 41 import org.pdfbox.exceptions.CryptographyException; 42 import org.pdfbox.exceptions.InvalidPasswordException; 43 44 import org.pdfbox.pdmodel.PDDocument; 45 import org.pdfbox.pdmodel.PDDocumentCatalog; 46 47 53 public class PrintFields 54 { 55 56 63 public void printFields( PDDocument pdfDocument ) throws IOException 64 { 65 PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); 66 PDAcroForm acroForm = docCatalog.getAcroForm(); 67 List fields = acroForm.getFields(); 68 Iterator fieldsIter = fields.iterator(); 69 70 System.out.println(new Integer (fields.size()).toString() + " top-level fields were found on the form"); 71 72 while( fieldsIter.hasNext()) 73 { 74 PDField field = (PDField)fieldsIter.next(); 75 processField(field, "|--", field.getPartialName()); 76 } 77 } 78 79 private void processField(PDField field, String sLevel, String sParent) throws IOException 80 { 81 List kids = field.getKids(); 82 if(kids != null) 83 { 84 Iterator kidsIter = kids.iterator(); 85 if(!sParent.equals(field.getPartialName())) 86 { 87 sParent = sParent + "." + field.getPartialName(); 88 } 89 System.out.println(sLevel + sParent); 90 while(kidsIter.hasNext()) 92 { 93 Object pdfObj = kidsIter.next(); 94 if(pdfObj instanceof PDField) 95 { 96 PDField kid = (PDField)pdfObj; 97 processField(kid, "| " + sLevel, sParent); 98 } 99 } 100 } 101 else 102 { 103 String outputString = sLevel + sParent + "." + field.getPartialName() + " = " + field.getValue() + 104 ", type=" + field.getClass().getName(); 105 106 System.out.println(outputString); 107 } 108 } 109 110 120 public static void main(String [] args) throws IOException , CryptographyException 121 { 122 PDDocument pdf = null; 123 try 124 { 125 if( args.length != 1 ) 126 { 127 usage(); 128 } 129 else 130 { 131 pdf = PDDocument.load( args[0] ); 132 PrintFields exporter = new PrintFields(); 133 if( pdf.isEncrypted() ) 134 { 135 try 136 { 137 pdf.decrypt( "" ); 138 } 139 catch( InvalidPasswordException e ) 140 { 141 System.err.println( "Error: The document is encrypted." ); 142 usage(); 143 } 144 } 145 exporter.printFields( pdf ); 146 } 147 } 148 finally 149 { 150 if( pdf != null ) 151 { 152 pdf.close(); 153 } 154 } 155 } 156 159 private static void usage() 160 { 161 System.err.println( "usage: org.pdfbox.examples.fdf.PrintFields <pdf-file>" ); 162 } 163 } | Popular Tags |