如何在PDFBox API 2中获取字段页面? [英] how to get field page in PDFBox API 2?

查看:53
本文介绍了如何在PDFBox API 2中获取字段页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中获取字段页面,而且我不知道如何获取每个字段的页码.我有这个代码:

i'm trying to get the field page in my project, and i dont know how to get the page number for each field and field. i have this code:

    String formTemplate = "Template.pdf";
    String filledForm = "filledForm.pdf";
    PDDocument pdfDocument = PDDocument.load(new File(formTemplate));

    PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

    if (acroForm != null)
    {

        PDField field = acroForm.getField( "name" );
        field.getAcroForm().setNeedAppearances(true);
        field.setValue("my name");
        acroForm.getField( "date" );
        field.setValue("my date");


    }

    pdfDocument.save(filledForm);
    pdfDocument.close();
}

如何获取字段的页码?

谢谢罗恩

推荐答案

这将向您显示该字段出现在哪个页面(从0开始)上:

This will show you on what page(s) (0-based) the field appears:

PDField field = acroForm.getField( "date" );
for (PDAnnotationWidget widget : field.getWidgets())
{
    PDPage page = widget.getPage();
    if (page == null)
    {
        // incorrect PDF. Plan B: try all pages to check the annotations.
        for (int p = 0; p < doc.getNumberOfPages(); ++p)
        {
            List<PDAnnotation> annotations = doc.getPage(p).getAnnotations();
            for (PDAnnotation ann : annotations)
            {
                if (ann.getCOSObject() == widget.getCOSObject())
                {
                    System.out.println("found at page: " + p);
                    break;
                }
            }
        }
        continue;
    }
    int pageNum = pdfDocument.getPages().indexOf(page);
    System.out.println("found at page: " + pageNum);
}

这篇关于如何在PDFBox API 2中获取字段页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆