Reputation: 29
[EDIT]I came here to ask if someone can help me ...
With Itext 7, I cannot understand how to set "fields comb" after I get those ?
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());
}
And this is how I close it :
form.setNeedApparences(true)
//form.flattenFields();
pdf.close();
InputStream streamFinal = new ByteArrayInputStream(out.toByteArray());
vo.setFile(new DefaultStreamedContent(streamFinal, "application/pdf", "result.pdf"));
What is strange is with the form generated (with flatten fields), all is perfect but if I set true to form#flattendfields the text in fields are shown as simple string and no comb...
Upvotes: 0
Views: 760
Reputation: 12302
First of all, one small remark: it's better to use the friendly PdfTextFormField#setComb
API than using low-level flag setting API. Low-level flags are not always meaningful, e.g. comb field flag should be applied to text fields and not just arbitrary fields.
Thus, you should perform this check and set the flag accordingly:
PdfFormField field = form.getField("ENTREPRISE");
if (field instanceof PdfTextFormField) {
((PdfTextFormField) field).setComb(true);
}
Next to that, it is meaningful to read the documentation of setComb
method which says the following:
* 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.
So you should note that you cannot make the field comb e.g. if it is a password field or a multiline one, and in any case you must set the max len of the field so that the PDF viewer knows how to display the field. You can do that with PdfTextFormField#setMaxLen
. So the complete code:
if (field instanceof PdfTextFormField) {
((PdfTextFormField) field).setComb(true);
((PdfTextFormField) field).setMaxLen(20);
}
P.S. These are just the obvious things that are missing in the code, but there may be more, and it is always valuable to attach the specific PDF you have problems with.
Upvotes: 1