[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"));
奇怪的是生成的表单(具有扁平字段)是完美的,但是如果我将true设置为form#flattendfields,则字段中的文本将显示为简单字符串,而不是梳子。
答案 0 :(得分: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);
}
P.S。这些只是代码中缺少的显而易见的东西,但可能还有更多,并且附加有问题的特定PDF总是很有价值的。