如何使用pdfbox获取PDF表单文本字段的内容?

Vol*_*osh 3 java pdf pdfbox

我正在使用它来获取使用 org.apache.pdfbox 的 PDF 文件的文本

File f = new File(fileName);  
      if (!f.isFile()) {
             System.out.println("File " + fileName + " does not exist.");
         return null;
    }

        try {
            parser = new PDFParser(new FileInputStream(f));
        } catch (Exception e) {
             System.out.println("Unable to open PDF Parser.");
            return null;
        }
   try {
           parser.parse();
             cosDoc = parser.getDocument();
           pdfStripper = new PDFTextStripper();           
          pdDoc = new PDDocument(cosDoc);
            parsedText = pdfStripper.getText(pdDoc);
        } catch (Exception e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

它非常适合我迄今为止使用过的 PDF。现在我有一个 PDF 表单,其中包含可编辑的文本字段。我的代码不返回字段内的文本。我想得到那个文本。有没有办法使用 PDFBox 获取它?

小智 7

这是您获取 AcroForms 键/值的方式:(此特定程序将其打印到控制台。)

package pdf_form_filler;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.form.*;
import java.io.File;
import java.util.*;

public class pdf_form_filler {

    public static void listFields(PDDocument doc) throws Exception {
        PDDocumentCatalog catalog = doc.getDocumentCatalog();
        PDAcroForm form = catalog.getAcroForm();
        List<PDFieldTreeNode> fields = form.getFields();

        for(PDFieldTreeNode field: fields) {
            Object value = field.getValue();
            String name = field.getFullyQualifiedName();
            System.out.print(name);
            System.out.print(" = ");
            System.out.print(value);
            System.out.println();
        }
    }

    public static void main(String[] args) throws Exception {
        File file = new File("test.pdf");
        PDDocument doc = PDDocument.load(file);
        listFields(doc);
    }

}
Run Code Online (Sandbox Code Playgroud)