Changing the alignment of a field

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

31st May 2016
iText PDF

Switch code for this example

AlignField.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to:
  10.  * http://stackoverflow.com/questions/24301578/align-acrofields-in-java
  11.  */
  12. package com.itextpdf.samples.sandbox.acroforms;
  13.  
  14. import com.itextpdf.forms.PdfAcroForm;
  15. import com.itextpdf.forms.fields.PdfFormField;
  16. import com.itextpdf.kernel.pdf.PdfDocument;
  17. import com.itextpdf.kernel.pdf.PdfReader;
  18. import com.itextpdf.kernel.pdf.PdfWriter;
  19. import com.itextpdf.samples.GenericTest;
  20. import com.itextpdf.test.annotations.type.SampleTest;
  21.  
  22. import org.junit.experimental.categories.Category;
  23.  
  24. import java.io.File;
  25. import java.util.Map;
  26.  
  27. @Category(SampleTest.class)
  28. public class AlignField extends GenericTest {
  29.     public static final String DEST = "./target/test/resources/sandbox/acroforms/align_field.pdf";
  30.     public static final String SRC = "./src/test/resources/pdfs/subscribe.pdf";
  31.  
  32.     public static void main(String[] args) throws Exception {
  33.         File file = new File(DEST);
  34.         file.getParentFile().mkdirs();
  35.         new AlignField().manipulatePdf(DEST);
  36.     }
  37.  
  38.     @Override
  39.     protected void manipulatePdf(String dest) throws Exception {
  40.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  41.         PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
  42.  
  43.         Map fields = form.getFormFields();
  44.         PdfFormField field;
  45.  
  46.         field = fields.get("personal.name");
  47.         field.setJustification(PdfFormField.ALIGN_LEFT);
  48.         field.setValue("Test");
  49.  
  50.         field = fields.get("personal.loginname");
  51.         field.setJustification(PdfFormField.ALIGN_CENTER);
  52.         field.setValue("Test");
  53.  
  54.         field = fields.get("personal.password");
  55.         field.setJustification(PdfFormField.ALIGN_RIGHT);
  56.         field.setValue("Test");
  57.  
  58.         field = fields.get("personal.reason");
  59.         field.setValue("Test");
  60.  
  61.         pdfDoc.close();
  62.     }
  63. }
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