【问题标题】:Get page from found AcroForm form field [duplicate]从找到的 AcroForm 表单字段中获取页面 [重复]
【发布时间】:2020-11-25 17:35:08
【问题描述】:

我有一个现有的 PDF,我想打开它并将内容添加到特定 PDField(或特别是 PDTerminalField,我认为这并不重要)所在的页面。 它可能在第一页或任何后面的页面上。
我知道该字段的名称,因此我可以查找它,甚至可以获取它在该页面上的尺寸和位置 (DRectangle mediabox = new PDRectangle((COSArray) fieldDict.getDictionaryObject(COSName.RECT));)

但是我找不到获取页面编号/索引的方法,所以我可以在正确的页面上书写。

PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
PDField docField = acroForm.getField("the_coolest_field");

int page = docField.???  // This is the missing part.


PDPageContentStream contentStream = new PDPageContentStream(pdfDocument, 
pdfDocument.getPage(page), PDPageContentStream.AppendMode.APPEND, true);
// now write something on the page where the field is in.

【问题讨论】:

    标签: java pdfbox acrofields


    【解决方案1】:

    使用this comment 中给出的提示,我可以创建一个包含字段名称和它出现的(最后)页面的地图。

    HashMap<String, Integer> formFieldPages = new HashMap<>();
    for (int page_i = 0; page_i < pdf_document.getNumberOfPages(); page_i++) {
        List<PDAnnotation> annotations = pdf_document.getPage(page_i).getAnnotations(); //
        for (PDAnnotation annotation: annotations) {
            if (!(annotation instanceof PDAnnotationWidget)) {
                System.err.println("Unknown annotation type " + annotation.getClass().getName() + ": " + annotation.toString());
                continue;
            }
            String name = ((PDAnnotationWidget)annotation).getCOSObject().getString(COSName.T);
            if (name == null) {
                System.err.println("Unknown widget name: " + annotation.toString());
                continue;
            }
            // make sure the field does not exists in the map
            if (formFieldPages.containsKey(name)) {
                System.err.println("Duplicated widget name, overwriting previous page value " + formFieldPages.get(name) + " with newly found page " + page_i + ": " + annotation.toString());
            }
            formFieldPages.put(name, page_i);
        }
    }
    

    现在查找页面就这么简单

    int page = formFieldPages.get(docField.getPartialName());
    

    请注意,如果该小部件由于某种原因不存在,这可能会引发 NullPointerException。


    下面的上一个答案。看来我对这种方法错误,但我保留它以供参考:

    我找到了/P 元素,它看起来可能是页面:

    int page = (int)currentField.getCOSObject().getCOSObject(COSName.P).getObjectNumber();
    page = page - 5; // I couldn't figure out why it's off by 4, but tests showed that the actual PDF page 1 (index [0]) is represented by `\P {4, 0}`, page 2 ([1]) is called "5", page 3 ([2]) is "6", etc.
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多