微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将相同名称的字段添加到pdf

如何解决如何将相同名称的字段添加到pdf

我正在使用itext 7.1.8,我需要向pdf添加具有相同名称的字段。我使用如下代码

public class Main {
    public static void main(String[] args) {
        final PdfDocument emptyPdfDocument = createEmptyPdfDocument(pdf);

        addTextField("Text_1","Hello",emptyPdfDocument.getFirstPage(),PdfAcroForm.getAcroForm(emptyPdfDocument,true),emptyPdfDocument);
        addTextField("Text_1",emptyPdfDocument.addNewPage(),emptyPdfDocument);
        savePdf(emptyPdfDocument);
    }

    private static void addTextField(String name,String value,pdfpage page,PdfAcroForm form,PdfDocument pdf) {
        PdfFormField field = form.getField(name);
        final Rectangle rect = new Rectangle(100,page.getCropBox().getHeight() - 100,300,20);
        if (field != null) {
            PdfWidgetAnnotation annotation = new PdfWidgetAnnotation(rect);
            annotation.makeIndirect(pdf);
            annotation.setVisibility(VISIBLE);
            field.addKid(annotation);
            page.addAnnotation(annotation);
            return;
        }

        field = PdfFormField.createText(pdf,rect,name);
        field.setValue(value);
        field.setVisibility(VISIBLE);
        page.addAnnotation(field.getWidgets().get(0));
        form.addField(field,page);
    }

    private static PdfDocument createEmptyPdfDocument(final String pdfPath) throws IOException {
        PdfWriter pdfWriter = new PdfWriter(new FileOutputStream(pdfPath));
        final PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        pdfDocument.addNewPage();
        return pdfDocument;
    }

    public static void savePdf(PdfDocument pdf) {
        pdf.close();
    }
}

但是第二次调用方法addTextField时,字段的孩子为空。

我不明白我在做什么错。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。