Tagged PDF: Adding Alt to the Structure Tree

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

2nd December 2015

Switch code for this example

 * This example was written in answer to the following question:
 * http://stackoverflow.com/questions/34036200
package sandbox.pdfa;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfString;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import sandbox.WrapToTest;

public class AddAltTags {
    public static final String SRC = "resources/pdfs/no_alt_attribute.pdf";
    public static final String DEST = "results/pdfa/added_alt_attributes.pdf";

    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        new AddAltTags().manipulatePdf(SRC, DEST);

    public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(src);
        PdfDictionary catalog = reader.getCatalog();
        PdfDictionary structTreeRoot = catalog.getAsDict(PdfName.STRUCTTREEROOT);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    public void manipulate(PdfDictionary element) {
        if (element == null)
        if (PdfName.FIGURE.equals(element.get(PdfName.S))) {
            element.put(PdfName.ALT, new PdfString("Figure without an Alt description"));
        PdfArray kids = element.getAsArray(PdfName.K);
        if (kids == null) return;
        for (int i = 0; i < kids.size(); i++)

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