iText pdf library
Website search

Changing the alignment of a field

iText 5 is no longer being developed, except for security fixes. Click the following link to see an updated example for iText 7.

This example was written in answer to the question How to align AcroFields?

AlignField.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
/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/24301578/align-acrofields-in-java
 */
package sandbox.acroforms;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import sandbox.WrapToTest;
 
@WrapToTest
public class AlignField {
 
    public static final String SRC = "resources/pdfs/subscribe.pdf";
    public static final String DEST = "results/acroforms/subscribe_realigned.pdf";
    
    public static void main(String[] args) throws DocumentException, IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AlignField().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();
        AcroFields.Item item;
        item = form.getFieldItem("personal.name");
        item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_LEFT));
        item = form.getFieldItem("personal.loginname");
        item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_CENTER));
        item = form.getFieldItem("personal.password");
        item.getMerged(0).put(PdfName.Q, new PdfNumber(PdfFormField.Q_RIGHT));
        form.setField("personal.name", "Test");
        form.setField("personal.loginname", "Test");
        form.setField("personal.password", "Test");
        form.setField("personal.reason", "Test");
        stamper.close();
        reader.close();
    }
}


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