Reputation: 31
Given a PDF template with notations of where to insert different info, my mission is to detect those notations and to replace them with dynamic data received from an html form. for instance, the template can look like this:
|FNAME||SNAME|
|TELCAP||PHONE1|
|CELLCAP||MOBILE|
|EMAIL|
|WEB|
and I have to replace |FNEME|
with a name I receive via a form.
Is there a way of getting the position of, for instance |FNAME|,
with iText
functions so I know where to insert the first name?
Also, after getting the position, is there a way of deleting
|FNAME|
and replacing it with the name received dynamically from
my html form?
Upvotes: 3
Views: 8481
Reputation: 13123
I don't know about getting the position of a "string" in a PDF with iText, but I know about getting the position of a form field in a PDF with iText. A form, in case you don't know the term, is a PDF document with fields that are named and might be fillable by an end-user if the form is presented in an environment where that's possible.
You create a PdfWriter and PdfReader, get the form template, and then a collection of what iText calls "AcroFields":
Document document = new Document(PageSize.LETTER, 18, 18, 18, 18);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(<<fileoutputpath>>);
DirectContent content = write.getDirectContent();
PdfReader reader = new PdfReader("<pdf form file specification>");
PdfImportedPage template = writer.getImportedPage(reader, 1); // gets first page
AcroFields acroFields = reader.getAcroFields();
the creator of the form will give a field name to each of the fillable fields; you can get the position and size of the rectangle covered by that field with that name:
float[] positions = acroFields.getFieldPositions("<fieldName>");
and then write your value to that position in place of the field name:
ColumnText columnText = new ColumnText(contentByte);
columnText.setSimpleColumn(new Phrase(value, fontToUse), pos1, pos2, pos3, pos4, Element.ALIGN_LEFT, false);
columnText.go(false);
I know this is pretty complicated, and unfortunately still incomplete, but I was reluctant to explain it fully before I/we even know that using a form is an option for you. The iText library will do this, but there's no simple way to do it that I know of.
Upvotes: 1