Skip to main content
Skip table of contents

How to underline a portion of text in a text field?

I have an application that uses iText to fill PDF form fields. One of these fields has some text with tags. I need the text enclosed in -tag to be underlined. How could I do that?

 For example:

U>This text/U> should be underlined. 
I need the text enclosed in -tag to be underlined. How could I do that?

Posted on StackOverflow on Feb 18, 2015 by Galma88

Ordinary text fields do not support rich text. If you want the fields to remain interactive, you will need RichText fields. These are fields that are flagged in a way that they accept an RV value.

If it is OK for you to flatten the form (i.e. remove all interactivity), then your code will look like this:

public void createPdf(String src, String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);

    Rectangle pos = form.getField("Name").getWidgets().get(0).getRectangle().toRectangle();

    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    InputSource is = new InputSource(new StringReader("
Bruno Lowagie

")); parser.parse(is, new CustomHandler(doc, pos)); pdfDoc.close(); }

Take a note that we use javax.xml.parsers.SAXParser to parse the HTML and put the CustomHandler instance as the second parameter. CustomHandler extends the org.xml.sax.helpers.DefaultHandler and overrides required methods for [blockcode]

[/blockcode] and tags like this:
public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("div".equals(qName)) {
            document.add(paragraph.setFixedPosition(position.getLeft(), position.getBottom(), position.getWidth()));
            paragraph = new Paragraph();
        } else if ("u".equals(qName)) {
            isUnderlined = false;

Please take a look at the FillWithUnderline example for the full code.

If you want to parse the HTML into iText objects using XML Worker, please follow this link to see the solution in iText 5 version.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.