itext7

How to manually add alternative text to an Image in iText 7


I am not interested in this solution of cycling through a finished PDFDocument to see which element is a Figure and if so dynamically add alternative text. It looks like a hack to me.

public void manipulate(PdfDictionary element) {
    if (element == null) {
        return;
    }

    // If an element is a figure, adds an /Alt entry.
    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;
    }

    // Loops over all the kids
    for (int i = 0; i < kids.size(); i++) {
        manipulate(kids.getAsDictionary(i));
    }
}

Rather, what I want is to explicitly specify alternative text for a given Image at construction time:

    ClassPathResource resourceLogo = new ClassPathResource(PDF_LOGO_FILENAME);
    File fileLogo = resourceLogo.getFile();
    ImageData logoData = ImageDataFactory.create(fileLogo.getAbsolutePath());
    Image logo = new Image(logoData);
    // ... Where is the .setAlternativeText here either for Image or ImageData?
    // e.g. logo.setAltText(..), logoData.setAltText(..)
    p.add(logo);
 

Solution

  • Found the answer here - Add AltText to image Itext 7 version9

    logo.getAccessibilityProperties().setAlternateDescription("My Alt Text");