Renaming a field

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

7th November 2015
admin-marketing

Switch code for this example

RenameField.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/21344750/itextsharp-renamefield-bug
  4.  *
  5.  * When renaming a field, you need to respect the existing hierarchy.
  6.  */
  7. package sandbox.acroforms;
  8.  
  9. import com.itextpdf.text.DocumentException;
  10. import com.itextpdf.text.pdf.AcroFields;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.PdfStamper;
  13.  
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.util.Map;
  18. import sandbox.WrapToTest;
  19.  
  20. @WrapToTest
  21. public class RenameField {
  22.  
  23.     public static final String SRC = "resources/pdfs/subscribe.pdf";
  24.     public static final String DEST = "results/acroforms/subscribe_renamed.pdf";
  25.    
  26.     public static void main(String[] args) throws DocumentException, IOException {
  27.         File file = new File(DEST);
  28.         file.getParentFile().mkdirs();
  29.         new RenameField().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.         form.renameField("personal.loginname", "personal.login");
  37.         stamper.close();
  38.         reader.close();
  39.         reader = new PdfReader(dest);
  40.         form = reader.getAcroFields();
  41.         Map fields = form.getFields();
  42.         for (String name : fields.keySet()) {
  43.             System.out.println(name);
  44.         }
  45.     }
  46. }
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