从找到的acroform字段获取页面

kiz8lqtg  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(329)

这个问题在这里已经有了答案

如何在pdfbox api 2中获取字段页(1个答案)
上个月关门了。
我有一个现有的pdf,我想打开,并添加内容的网页,其中一个特定的 PDField (或者具体地说 PDTerminalField ,我不认为这是重要的)是。可能在第一页,也可能在以后的任何一页。
我知道这个字段的名称,通过它,我可以查找它,甚至可以得到它在那个页面上的尺寸和位置( DRectangle mediabox = new PDRectangle((COSArray) fieldDict.getDictionaryObject(COSName.RECT)); )
但是,我找不到一种方法来获取它所在页面的编号/索引,因此我可以在正确的页面上进行写作。

  1. PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
  2. PDField docField = acroForm.getField("the_coolest_field");
  3. int page = docField.??? // This is the missing part.
  4. PDPageContentStream contentStream = new PDPageContentStream(pdfDocument,
  5. pdfDocument.getPage(page), PDPageContentStream.AppendMode.APPEND, true);
  6. // now write something on the page where the field is in.
dy1byipe

dy1byipe1#

使用这个注解中给出的提示,我可以创建一个包含字段名和它出现的(最后一个)页面的Map。

  1. HashMap<String, Integer> formFieldPages = new HashMap<>();
  2. for (int page_i = 0; page_i < pdf_document.getNumberOfPages(); page_i++) {
  3. List<PDAnnotation> annotations = pdf_document.getPage(page_i).getAnnotations(); //
  4. for (PDAnnotation annotation: annotations) {
  5. if (!(annotation instanceof PDAnnotationWidget)) {
  6. System.err.println("Unknown annotation type " + annotation.getClass().getName() + ": " + annotation.toString());
  7. continue;
  8. }
  9. String name = ((PDAnnotationWidget)annotation).getCOSObject().getString(COSName.T);
  10. if (name == null) {
  11. System.err.println("Unknown widget name: " + annotation.toString());
  12. continue;
  13. }
  14. // make sure the field does not exists in the map
  15. if (formFieldPages.containsKey(name)) {
  16. System.err.println("Duplicated widget name, overwriting previous page value " + formFieldPages.get(name) + " with newly found page " + page_i + ": " + annotation.toString());
  17. }
  18. formFieldPages.put(name, page_i);
  19. }
  20. }

现在查找页面就像

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

请注意,如果由于某种原因该小部件不存在,这可能会引发nullpointerexception。
前面的答案如下。看来我的方法是错的,但我保留它作为参考。
我找到了 /P 元素,看起来像是页面:

  1. int page = (int)currentField.getCOSObject().getCOSObject(COSName.P).getObjectNumber();
  2. 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.
展开查看全部

相关问题