Changing the author of an annotation

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

31st May 2016
admin-marketing

Switch code for this example

ChangeAuthor.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.  * This example was written by Bruno Lowagie in answer to the following question:
  10.  * https://www.linkedin.com/groups/Script-Change-Author-Name-Comments-159987.S.5984062085800144899
  11.  */
  12. package com.itextpdf.samples.sandbox.interactive;
  13.  
  14. import com.itextpdf.kernel.pdf.*;
  15. import com.itextpdf.samples.GenericTest;
  16. import com.itextpdf.test.annotations.type.SampleTest;
  17.  
  18. import org.junit.experimental.categories.Category;
  19.  
  20. import java.io.File;
  21. import java.io.IOException;
  22.  
  23. @Category(SampleTest.class)
  24. public class ChangeAuthor extends GenericTest {
  25.     public static final String DEST = "./target/test/resources/sandbox/interactive/change_author.pdf";
  26.     public static final String SRC = "./src/test/resources/pdfs/page229_annotations.pdf";
  27.  
  28.     public static void main(String[] args) throws IOException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new ChangeAuthor().manipulatePdf(DEST);
  32.     }
  33.  
  34.     public void manipulatePdf(String dest) throws IOException {
  35.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  36.  
  37.         PdfDictionary pageDict = pdfDoc.getFirstPage().getPdfObject();
  38.         PdfArray annots = pageDict.getAsArray(PdfName.Annots);
  39.         if (annots != null) {
  40.             for (int i = 0; i < annots.size(); i++) {
  41.                 changeAuthor(annots.getAsDictionary(i));
  42.             }
  43.         }
  44.  
  45.         pdfDoc.close();
  46.     }
  47.  
  48.     public void changeAuthor(PdfDictionary annotation) {
  49.         if (annotation == null) {
  50.             return;
  51.         }
  52.         PdfString t = annotation.getAsString(PdfName.T);
  53.         if (t == null) {
  54.             return;
  55.         }
  56.         if ("iText".equals(t.toString())) {
  57.             annotation.put(PdfName.T, new PdfString("Bruno Lowagie"));
  58.         }
  59.     }
  60. }
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