【问题标题】:Itext 7 - Comb field - filling out formsItext 7 - 梳状字段 - 填写表格
【发布时间】:2019-07-31 23:59:44
【问题描述】:

[EDIT]我来这里是想问是否有人可以帮助我...

使用 Itext 7,我无法理解如何设置“字段梳”?

PdfWriter writer = new PdfWriter(out);
InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/resources/pdf/test.pdf");
PdfDocument pdf = new PdfDocument(new PdfReader(stream), writer);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();

PdfFormField field = fields.get("ENTREPRISE");

    if(field instanceof PdfTextFormField){
        ((PdfTextFormField) field).setMaxLen(30);
        ((PdfTextFormField) field).setComb(true);
        ((PdfTextFormField) field).setMultiline(false);
        ((PdfTextFormField) field).setPassword(false);
        ((PdfTextFormField) field).setFileSelect(false);
        field.setValue(vo.getNomEntreprise());
    }     

这就是我关闭它的方式:

    form.setNeedApparences(true)
//form.flattenFields();
        pdf.close();
        InputStream streamFinal = new ByteArrayInputStream(out.toByteArray());
        vo.setFile(new DefaultStreamedContent(streamFinal, "application/pdf", "result.pdf"));

奇怪的是生成的表单(带有展平字段),一切都很完美,但如果我将 form#flattendfields 设置为 true,字段中的文本将显示为简单字符串且没有梳...

【问题讨论】:

    标签: itext itext7


    【解决方案1】:

    首先,要注意一点:使用友好的PdfTextFormField#setComb API 比使用低级标志设置API 更好。低级标志并不总是有意义的,例如梳字段标志应应用于文本字段,而不仅仅是任意字段。

    因此,您应该执行此检查并相应地设置标志:

    PdfFormField field = form.getField("ENTREPRISE");
    if (field instanceof PdfTextFormField) {
        ((PdfTextFormField) field).setComb(true);
    }
    

    除此之外,阅读setComb 方法的文档是有意义的:

     * Meaningful only if the MaxLen entry is present in the text field dictionary
     * and if the Multiline, Password, and FileSelect flags are clear.
     * If true, the field is automatically divided into as many equally spaced positions,
     * or combs, as the value of MaxLen, and the text is laid out into those combs.
    

    所以你应该注意你不能使字段梳理例如如果它是密码字段或多行字段,并且在任何情况下您都必须设置该字段的最大长度,以便 PDF 查看器知道如何显示该字段。你可以通过PdfTextFormField#setMaxLen 做到这一点。所以完整的代码:

    if (field instanceof PdfTextFormField) {
        ((PdfTextFormField) field).setComb(true);
        ((PdfTextFormField) field).setMaxLen(20);
    }
    

    附:这些只是代码中缺少的明显内容,但可能还有更多,附加您遇到问题的特定 PDF 总是很有价值的。

    【讨论】:

    • 你好@Alexey Subach!感谢您的回答:) 我编辑了我的帖子,做了一些小的改动,但没有用.. 我添加了关闭表单的方式,......以及生成的 pdf(没有展平字段).. 事实上,当你点击时一个字段,你可以看到它们是梳子,否则没有...... :( :(
    • 我编辑了我的帖子!现在,当我将needApparences 设置为true 时,它​​是完美的,所有字段都是comb。不需要设置comb,maxlen,......已经由Adobe 完成(当我创建pdf 时)。但是现在,当我将 flattendfields 设置为 true 时,所有梳子都丢失了.. :((
    • 我找到了解决方案!我使用的是旧版本的 itext... 需要使用更新的 ^^ 再次感谢您!
    猜你喜欢
    • 2018-02-04
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2021-04-23
    • 2017-08-06
    • 2020-03-31
    相关资源
    最近更新 更多