Underline a form field value

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

6th November 2015
admin-marketing

Switch code for this example

FillWithUnderline.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/28579382/underline-portion-of-text-using-itextsharp
  4.  */
  5. package sandbox.acroforms;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.Element;
  9. import com.itextpdf.text.pdf.AcroFields;
  10. import com.itextpdf.text.pdf.AcroFields.FieldPosition;
  11. import com.itextpdf.text.pdf.ColumnText;
  12. import com.itextpdf.text.pdf.PdfReader;
  13. import com.itextpdf.text.pdf.PdfStamper;
  14. import com.itextpdf.tool.xml.ElementList;
  15. import com.itextpdf.tool.xml.XMLWorkerHelper;
  16.  
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import sandbox.WrapToTest;
  21.  
  22. @WrapToTest
  23. public class FillWithUnderline {
  24.  
  25.     public static final String SRC = "resources/pdfs/form.pdf";
  26.     public static final String DEST = "results/acroforms/field_underlined.pdf";
  27.    
  28.  
  29.     public static void main(String[] args) throws DocumentException, IOException {
  30.         File file = new File(DEST);
  31.         file.getParentFile().mkdirs();
  32.         new FillWithUnderline().manipulatePdf(SRC, DEST);
  33.     }
  34.  
  35.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  36.         PdfReader reader = new PdfReader(src);
  37.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  38.         stamper.setFormFlattening(true);
  39.         AcroFields form = stamper.getAcroFields();
  40.         FieldPosition pos = form.getFieldPositions("Name").get(0);
  41.         ColumnText ct = new ColumnText(stamper.getOverContent(pos.page));
  42.         ct.setSimpleColumn(pos.position);
  43.         ElementList elements = XMLWorkerHelper.parseToElementList("Bruno Lowagie", null);
  44.         for (Element element : elements) {
  45.             ct.addElement(element);
  46.         }
  47.         ct.go();
  48.         stamper.close();
  49.     }
  50. }
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