Underline a form field value

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

6th November 2015

Switch code for this example

 * Example written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/28579382/underline-portion-of-text-using-itextsharp
package sandbox.acroforms;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.AcroFields.FieldPosition;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import sandbox.WrapToTest;

public class FillWithUnderline {

    public static final String SRC = "resources/pdfs/form.pdf";
    public static final String DEST = "results/acroforms/field_underlined.pdf";

    public static void main(String[] args) throws DocumentException, IOException {
        File file = new File(DEST);
        new FillWithUnderline().manipulatePdf(SRC, DEST);

    public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        AcroFields form = stamper.getAcroFields();
        FieldPosition pos = form.getFieldPositions("Name").get(0);
        ColumnText ct = new ColumnText(stamper.getOverContent(pos.page));
        ElementList elements = XMLWorkerHelper.parseToElementList("
Bruno Lowagie
", null); for (Element element : elements) { ct.addElement(element); } ct.go(); stamper.close(); } }

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