Underline a form field value

This is a code example of iText PDF, discover more.

31st May 2016
iText PDF

This example was written in answer to the question How to underline a portion of text in a text field?

FillWithUnderline.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
/**
 * Example written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/28579382/underline-portion-of-text-using-itextsharp
 */
package com.itextpdf.samples.sandbox.acroforms;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.StringReader;
 
@Category(SampleTest.class)
public class FillWithUnderline extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/fill_with_underline.pdf";
    public static final String SRC = "./src/test/resources/pdfs/form.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillWithUnderline().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(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);
        form.flattenFields();
 
        Rectangle pos = form.getField("Name").getWidgets().get(0).getRectangle().toRectangle();
 
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        InputSource is = new InputSource(new StringReader("<root><div>Bruno <u>Lowagie</u></div></root>"));
        parser.parse(is, new CustomHandler(doc, pos));
 
        pdfDoc.close();
    }
 
 
    private static class CustomHandler extends DefaultHandler {
        protected Document document;
        protected Rectangle position;
        protected Paragraph paragraph;
        protected boolean isUnderlined;
 
        public CustomHandler(Document document, Rectangle position) {
            this.document = document;
            this.position = position;
            paragraph = new Paragraph();
            isUnderlined = false;
        }
 
        /**
         * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
         * java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if ("u".equals(qName)) {
                isUnderlined = true;
            }
        }
 
        /**
         * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
         * java.lang.String, java.lang.String)
         */
        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()));
                position.moveDown(20);
                paragraph = new Paragraph();
            } else if ("u".equals(qName)) {
                isUnderlined = false;
            }
        }
 
        /**
         * @see org.xml.sax.ContentHandler#characters(char[], int, int)
         */
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            Text text = new Text(strip(new StringBuffer().append(ch, start, length)));
            if (isUnderlined) {
                text.setUnderline();
            }
            if (0 != text.getText().length()) {
                paragraph.add(text);
            }
        }
 
        /**
         * Replaces all the newline characters by a space.
         *
         * @param buf the original StringBuffer
         * @return a String without newlines
         */
        protected String strip(StringBuffer buf) {
            while (buf.length() != 0 && (buf.charAt(0) == '\n' || buf.charAt(0) == '\t')) {
                buf.deleteCharAt(0);
            }
            while (buf.length() != 0 && (buf.charAt(0) == '\n' || buf.charAt(0) == '\t'))
                buf.deleteCharAt(buf.length() - 1);
            return buf.toString();
        }
    }
}

Click the following link to see the legacy example for iText 5. Except for security fixes, iText 5 is no longer being developed.



Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now