iText find position of text in pdf
<p>I am creating a utility that will add a multi-line text field just below the last line of text in an existing PDF document. This will be used for people who want to add comments to a report that is generated from another system.</p>

<p>I followed the examples from the iText book, and also looked at this SO question: <a href="https://stackoverflow.com/questions/13632541/get-the-exact-stringposition-in-pdf">Get the exact Stringposition in PDF</a></p>

<p>So now I've got a method that parses the last page of the document and a custom listener that finds the coordinates of the text I'm looking for.</p>

<p>Here is my code parsing method:</p>

<pre><code>private void parsePdfPage2(String src, int pageNum) throws IOException {
    PdfReader reader = new PdfReader(src);

    RenderListener listener = new MyTextRenderListener();
    PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
    PdfDictionary pageDic = reader.getPageN(pageNum);
    PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
    processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNum), resourcesDic);
}
</code></pre>

<p>And here is the listener:</p>

<pre><code>public class MyTextRenderListener implements RenderListener {
@Override
public void beginTextBlock() {}

@Override
public void endTextBlock() {}

@Override
public void renderImage(ImageRenderInfo renderInfo) {}

@Override
public void renderText(TextRenderInfo renderInfo) {
    // Check if this is the text marker
    String text = renderInfo.getText();
    if (text.equalsIgnoreCase("Comments")) {
        // Found it
        LineSegment ls = renderInfo.getBaseline(); 
        System.out.println("Found at X: " + ls.getBoundingRectange().getX() +
                ",  Y: " + ls.getBoundingRectange().getY());
    }
}
}
</code></pre>

<p>However, now I need to send the found LineSegment object (or the individual coordinates) back to the original parsing method. Of course I could write the values to disk and read it in the parsing method, but that seems horrible. I'm pretty sure there is a more elegant way to achieve this and would appreciate pointers.</p>