Check Text Rendering Mode: Ensure that the text rendering mode is correctly set to invisible. The code snippet you provided seems correct, but double-check that PdfContentByte.TEXT_RENDER_MODE_INVISIBLE is properly applied.
Text Search Method: The method you're using to search for the text (pdfWriter.getDirectContent().toString().contains("invisible text here")) might not be the most reliable. The toString() method on PdfContentByte might not return the exact content you expect.
Alternative Identification Method: Instead of using invisible text, consider using a different method to identify the page. For example, you could add a custom property or a hidden annotation to the page that you can check in onEndPage().
Debugging: Add logging or debugging statements to verify that the invisible text is being added correctly and that the onEndPage() method is being called as expected.
iText Version: Ensure you are using a compatible version of iText. Sometimes, behavior can differ between versions.