Reputation: 125
I want to set a field name in a pdf (not in existing pdf) so that I can get the coordinates of that field when required. Can we achieve this without pdfstamper?
Thanks in advance
Upvotes: 2
Views: 1100
Reputation: 77606
You say you want to create a PDF from scratch (not an existing PDF) and you want this PDF to have a field.
Creating a PDF from scratch doesn't involve PdfStamper
, so the answer to the question "Can we achieve this without PdfStamper
" is "Yes, you can."
If you are thinking about using iText 5, you should take a look at the following examples:
One of those examples was written in answer to the question Add PdfPCell to Paragraph
In this example, we create a Paragraph
in which some Chunk
objects are fields:
You can get the coordinates of those fields using the getFieldPositions()
method. That is explained in the FAQ: How to find the absolute position and dimension of a field?
If you are thinking of using iText 7.0.1, you will discover that the classes are much easier to understand because the same classes are used regardless whether you are creating a form from scratch or filling out an existing form, see chapter 4 of the iText 7 jump-start tutorial.
public class GenericFields extends GenericTest {
public static final String DEST = "./target/test/resources/sandbox/events/generic_fields.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new GenericFields().manipulatePdf(DEST);
}
@Override
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Paragraph p = new Paragraph();
p.add("The Effective Date is ");
Text day = new Text(" ");
day.setNextRenderer(new FieldTextRenderer(day, "day"));
p.add(day);
p.add(" day of ");
Text month = new Text(" ");
month.setNextRenderer(new FieldTextRenderer(month, "month"));
p.add(month);
p.add(", ");
Text year = new Text(" ");
year.setNextRenderer(new FieldTextRenderer(year, "year"));
p.add(year);
p.add(" that this will begin.");
doc.add(p);
doc.close();
}
protected class FieldTextRenderer extends TextRenderer {
protected String fieldName;
public FieldTextRenderer(Text textElement, String fieldName) {
super(textElement);
this.fieldName = fieldName;
}
@Override
public void draw(DrawContext drawContext) {
PdfTextFormField field = PdfTextFormField.createText(drawContext.getDocument(), getOccupiedAreaBBox(), fieldName);
PdfAcroForm.getAcroForm(drawContext.getDocument(), true).addField(field);
}
}
}
Upvotes: 1