簡體   English   中英

如何使用pdfbox獲取PDF表單文本域的內容?

[英]How to get the content of PDF form text fields using 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();
        }

它非常適合我目前使用過的 PDF。 現在我有一個 PDF 表單,其中包含可編輯的文本字段。 我的代碼不返回字段內的文本。 我想得到那個文本。 有沒有辦法使用 PDFBox 獲取它?

這是您獲取 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);
    }

}

PDFieldTreeNode似乎不再受支持。 嘗試PDField

對於那些現在嘗試使用相同方法的人。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM