Search code examples
javastringitextescaping

Itext5 not able to render java escape sequence


Using itextpdf:5.0.6 to preapare a PDF. The text contains java escape sequences (tab: \t, newline: \n, backspace: \b, formfeed: \f, carriage return: \r).

It is able to render newline but treating tab (\t) as a single space. Not able to render formfeed, backspace. Need a way to render the Java string as expected in the PDF.

Font used: Courier
Java String = Tab\tTab
Output in pdf = Tab Tab

Chunk chunk=new Chunk(string)
document.add(chunk)

Solution

  • In this case your expectations are the problem: The Chunk class simply does neither promise nor implement special handling of those control characters, only \n is supported to indicate a line break and \t is handled just like a space.

    If you need TABs in your code, consider using TAB Chunks (see this old answer) or section 2.2.6 The DrawInterface: vertical position marks, separators, and tabs in iText in Action, 2nd edition (currently you can see the entire book for free here).

    Thus, if you Need a way to render the Java string as expected in the PDF, you have to parse your Java string for those control characters, split the string there, and handle each part in a way that results in an appearance as you expect it.


    As an aside, iText 5.0.6 is ancient. You should consider updating.