Tagged PDF: Adding Alt to the Structure Tree

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

31st May 2016
iText PDF

Switch code for this example

AddAltTags.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 in answer to the following question:
  10.  * http://stackoverflow.com/questions/34036200
  11.  */
  12. package com.itextpdf.samples.sandbox.pdfa;
  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 AddAltTags extends GenericTest {
  25.     public static final String DEST = "./target/test/resources/sandbox/pdfa/add_alt_tags.pdf";
  26.     public static final String SRC = "./src/test/resources/pdfs/no_alt_attribute.pdf";
  27.  
  28.     public static void main(String[] args) throws Exception {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new AddAltTags().manipulatePdf(DEST);
  32.     }
  33.  
  34.     public void manipulatePdf(String dest) throws IOException {
  35.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  36.         PdfDictionary catalog = pdfDoc.getCatalog().getPdfObject();
  37.         PdfDictionary structTreeRoot = catalog.getAsDictionary(PdfName.StructTreeRoot);
  38.         manipulate(structTreeRoot);
  39.         pdfDoc.close();
  40.     }
  41.  
  42.     public void manipulate(PdfDictionary element) {
  43.         if (element == null) {
  44.             return;
  45.         }
  46.         if (PdfName.Figure.equals(element.get(PdfName.S))) {
  47.             element.put(PdfName.Alt, new PdfString("Figure without an Alt description"));
  48.         }
  49.         PdfArray kids = element.getAsArray(PdfName.K);
  50.         if (kids == null) {
  51.             return;
  52.         }
  53.         for (int i = 0; i < kids.size(); i++) {
  54.             manipulate(kids.getAsDictionary(i));
  55.         }
  56.     }
  57. }
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