Created
March 12, 2019 10:09
-
-
Save kishorek/f05b12c866b7ca449dcb1765a43a6015 to your computer and use it in GitHub Desktop.
Read PDF Acro Forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.pdfbox.pdmodel.PDDocument; | |
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; | |
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; | |
import org.apache.pdfbox.pdmodel.interactive.form.PDField; | |
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField; | |
import java.io.IOException; | |
import java.util.List; | |
public class PDFFormReader { | |
public static void main(String args[]) { | |
PDFFormReader obj = new PDFFormReader(); | |
obj.process(); | |
} | |
void process() { | |
// Load the PDF document created by SimpleForm.java | |
try { | |
PDDocument document = PDDocument.load(this.getClass().getResourceAsStream("ACORD70_edited.pdf")); | |
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); | |
//get all fields in form | |
List<PDField> fields = acroForm.getFields(); | |
System.out.println(fields.size() + " top-level fields were found on the form"); | |
//inspect field values | |
for (PDField field : fields) { | |
processField(field, "|--", field.getPartialName()); | |
} | |
} catch (InvalidPasswordException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void processField(PDField field, String sLevel, String sParent) throws IOException { | |
String partialName = field.getPartialName(); | |
if (field instanceof PDNonTerminalField) { | |
if (!sParent.equals(field.getPartialName())) { | |
if (partialName != null) { | |
sParent = sParent + "." + partialName; | |
} | |
} | |
System.out.println(sLevel + sParent); | |
for (PDField child : ((PDNonTerminalField) field).getChildren()) { | |
processField(child, "| " + sLevel, sParent); | |
} | |
} else { | |
//field has no child. output the value | |
String fieldValue = field.getValueAsString(); | |
StringBuilder outputString = new StringBuilder(sLevel); | |
outputString.append(sParent); | |
if (partialName != null) { | |
outputString.append(".").append(partialName); | |
} | |
outputString.append(" = ").append(fieldValue); | |
// outputString.append(", type=").append(field.getClass().getName()); | |
System.out.println(outputString); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment