Changing the alignment of a field

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

6th November 2015
admin-marketing

Switch code for this example

AlignField.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/24301578/align-acrofields-in-java
  4.  */
  5. package sandbox.acroforms;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.pdf.AcroFields;
  9. import com.itextpdf.text.pdf.PdfFormField;
  10. import com.itextpdf.text.pdf.PdfName;
  11. import com.itextpdf.text.pdf.PdfNumber;
  12. import com.itextpdf.text.pdf.PdfReader;
  13. import com.itextpdf.text.pdf.PdfStamper;
  14.  
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import sandbox.WrapToTest;
  19.  
  20. @WrapToTest
  21. public class AlignField {
  22.  
  23.     public static final String SRC = "resources/pdfs/subscribe.pdf";
  24.     public static final String DEST = "results/acroforms/subscribe_realigned.pdf";
  25.    
  26.     public static void main(String[] args) throws DocumentException, IOException {
  27.         File file = new File(DEST);
  28.         file.getParentFile().mkdirs();
  29.         new AlignField().manipulatePdf(SRC, DEST);
  30.     }
  31.  
  32.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  33.         PdfReader reader = new PdfReader(src);
  34.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  35.         AcroFields form = stamper.getAcroFields();
  36.         AcroFields.Item item;
  37.         item = form.getFieldItem("personal.name");
  38.         item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_LEFT));
  39.         item = form.getFieldItem("personal.loginname");
  40.         item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_CENTER));
  41.         item = form.getFieldItem("personal.password");
  42.         item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_RIGHT));
  43.         form.setField("personal.name", "Test");
  44.         form.setField("personal.loginname", "Test");
  45.         form.setField("personal.password", "Test");
  46.         form.setField("personal.reason", "Test");
  47.         stamper.close();
  48.         reader.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