Tagged PDF: Adding Alt to the Structure Tree

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

2nd December 2015
admin-marketing

Switch code for this example

AddAltTags.java
  1. /*
  2.  * This example was written in answer to the following question:
  3.  * http://stackoverflow.com/questions/34036200
  4.  */
  5. package sandbox.pdfa;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.pdf.PdfArray;
  9. import com.itextpdf.text.pdf.PdfDictionary;
  10. import com.itextpdf.text.pdf.PdfName;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.PdfStamper;
  13. import com.itextpdf.text.pdf.PdfString;
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import sandbox.WrapToTest;
  18.  
  19. @WrapToTest
  20. public class AddAltTags {
  21.    
  22.     public static final String SRC = "resources/pdfs/no_alt_attribute.pdf";
  23.     public static final String DEST = "results/pdfa/added_alt_attributes.pdf";
  24.  
  25.     public static void main(String[] args) throws IOException, DocumentException {
  26.         File file = new File(DEST);
  27.         file.getParentFile().mkdirs();
  28.         new AddAltTags().manipulatePdf(SRC, DEST);
  29.     }
  30.  
  31.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  32.         PdfReader reader = new PdfReader(src);
  33.         PdfDictionary catalog = reader.getCatalog();
  34.         PdfDictionary structTreeRoot = catalog.getAsDict(PdfName.STRUCTTREEROOT);
  35.         manipulate(structTreeRoot);
  36.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  37.         stamper.close();
  38.     }
  39.    
  40.     public void manipulate(PdfDictionary element) {
  41.         if (element == null)
  42.             return;
  43.         if (PdfName.FIGURE.equals(element.get(PdfName.S))) {
  44.             element.put(PdfName.ALT, new PdfString("Figure without an Alt description"));
  45.         }
  46.         PdfArray kids = element.getAsArray(PdfName.K);
  47.         if (kids == null) return;
  48.         for (int i = 0; i < kids.size(); i++)
  49.             manipulate(kids.getAsDict(i));
  50.     }
  51. }
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