0
votes

iText requires coordinates to create form fields and Page Number in existing PDFs at different places.

My PDF is dynamic. So I decided to creat the PDF with some identifier text. And use TextRenderInfo to find the coordinates for the text and use those coordinates to creat the textfields and other form fields.

ParsingHelloWorld.java
    public void extractText(String src, String dest) throws IOException, DocumentException  {
        PrintWriter out = new PrintWriter(new FileOutputStream(dest));
        PdfReader reader = new PdfReader(src);
        PdfStamper stp = new PdfStamper(reader, new FileOutputStream(dest);
        RenderListener listener = new MyTextRenderListener(out,reader,stp);
        PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);

    for ( int pageNum= 0; pageNum < reader.getNumberOfPages(); pageNum++ ){
        PdfDictionary pageDic = reader.getPageN(pageNum);

        PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
        processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNum), resourcesDic);
    }   

    out.flush();
    out.close();
    stp.close();

}

MyTextRenderListener.java public void renderText(TextRenderInfo renderInfo) {

if (renderInfo.getText().startsWith("Fill_in_TextField")){ // creates the text fields by getting co-ordinates form the renderinfo object. createTextField(renderInfo); }else if (renderInfo.getText().startsWith("Fill_in_SignatureField")){ // creates the text fields by getting co-ordinates form the renderinfo object. createSignatureField(renderInfo); } }

The problem is I have a page number in extractText method in the ParsingHelloWorld class. When the renderText method is called inside the MyTextRenderListener class internally processing the page content, I couldn't get the pageNumber to generate the fields in the PDF at the particular coordinates where the identifier text resides(ex Fill_in_TextField,Fill_in_SignatureField..etc ).

Any suggestions/ ideas to get the page number in my scenario.

Thanks in advance.

1
What about adding a page number member variable to your MyTextRenderListener which you set in your loop through the document pages and then can forward to the createTextField or createSignatureField method right next to the renderInfo argument. BTW, the test renderInfo.getText().startsWith("Fill_in_...") might fail if the original marker was inlined, and it might also fail in case of extra kerning applied.mkl

1 Answers

1
votes

That's easy. Add a parameter to MyTextListener:

protected int page;
public void setPage(int page) {
   this.page = page;
}

Now when you loop over the pages in ParsingHelloWorld, pass the page number to MyTextListener:

listener.setPage(pageNum);

Now you have access to that number in the renderText() method and you can pass it to your createTextField() method.

Note that I think your loop is wrong. Page numbers don't start at page 0, they start at page 1.