Add Image Alternative Text

This guide demonstrates how to add alternate text to images in a PDF document using UniPDF. Alternate text is crucial for accessibility, allowing screen readers to describe images to visually impaired users.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the accessibility folder in the unipdf-examples directory.

cd unipdf-examples/accessibility

How it works

The following example code demonstrates how to add an image to a PDF and set its alternate text.

Code Explanation

The code begins by initializing the metered license API key in the init function (lines 25-32) to ensure the library is properly licensed. In the main function (lines 34-92), a new creator.Creator is initialized to start building the PDF. A StructTreeRoot and a base KDictionary of type Document are created (lines 37-59) to establish the document’s structure tree, which is essential for accessibility.

A KDictionary representing a Section is then created (lines 62-66) to group the content logically. The addImage function (defined in lines 94-131) is called to handle the addition of images. This function loads the image from a file, draws it onto the page, and generates a corresponding KDictionary. Crucially, it sets the Alt property of this dictionary to the provided alternate text (line 115), ensuring screen readers can describe the image. Finally, the image’s structure element is added to the section, the StructTreeRoot is assigned to the creator, and the document is written to a file.

Run the code

Run this command to generate the PDF with image alt text.

go run pdf_add_image_alt_text.go

Sample output

The output file image_alt_text.pdf will contain the images with the specified alternate text, which can be verified using a PDF accessibility checker or screen reader.

Sample Output

Got any Questions?

We're here to help you.