SelectPdf for .NET 10 - Alternative Text for Images - C# / .NET 10 Sample

This sample shows how to use SelectPdf Library for .NET to describe the images of an existing tagged PDF document, the text a screen reader reads in place of an image. Missing descriptions are the most common reason a PDF fails PDF/UA. The figures are listed in reading order; type a description for each, or mark one that is only decoration as decorative.

Tagged PDF document (optional - without one, a tagged test document with two images is used, one of them not described):

Password (for a protected PDF):

Sample code · C#
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PdfAlternateTextModel : PageModel
    {
        // A figure of the document, as the page shows it: a thumbnail and its descriptions.
        public class FigureRow
        {
            public int Page { get; set; }
            public string Type { get; set; }
            public string Thumbnail { get; set; }
            public bool Missing { get; set; }
            public string AlternateText { get; set; }
            public bool Decorative { get; set; }
        }

        // An uploaded tagged PDF document, or nothing - a tagged test document is made then.
        [BindProperty]
        public IFormFile FilePdf { get; set; }

        [BindProperty]
        public string TxtPassword { get; set; }

        // The document between the two steps (listed, then fixed).
        [BindProperty]
        public string Document { get; set; }

        [BindProperty]
        public List<FigureRow> Figures { get; set; } = new List<FigureRow>();

        public void OnGet()
        {
        }

        // Step 1: list the figures of the document.
        public IActionResult OnPostList()
        {
            byte[] source;
            if (FilePdf != null && FilePdf.Length > 0)
            {
                using (var uploaded = new MemoryStream())
                {
                    FilePdf.CopyTo(uploaded);
                    source = uploaded.ToArray();
                }
            }
            else
            {
                source = TestDocument();
            }

            try
            {
                // load the tagged document (an untagged one is refused with the reason)
                using (PdfAccessibilityManager manager = new PdfAccessibilityManager())
                {
                    Load(manager, source);

                    // the figures in reading order, each with a thumbnail of its area of the page
                    var missing = new HashSet<PdfFigure>(manager.MissingAlternateText);
                    foreach (PdfFigure figure in manager.Figures)
                    {
                        Figures.Add(new FigureRow
                        {
                            Page = figure.PageIndex + 1,
                            Type = figure.Type,
                            Thumbnail = figure.PageIndex < 0 ? null : "data:image/png;base64," + Convert.ToBase64String(figure.GetImage(72)),
                            Missing = missing.Contains(figure),
                            AlternateText = figure.AlternateText,
                        });
                    }
                }
                Document = Convert.ToBase64String(source);
                if (Figures.Count == 0) ViewData["Message"] = "The document has no figures.";
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
            }
            ModelState.Clear();
            return Page();
        }

        // Step 2: write the descriptions and return the fixed document.
        public IActionResult OnPostFix()
        {
            byte[] source = Convert.FromBase64String(Document ?? "");
            try
            {
                using (PdfAccessibilityManager manager = new PdfAccessibilityManager())
                {
                    Load(manager, source);

                    // the figures are in the same order as listed
                    for (int i = 0; i < manager.Figures.Count && i < Figures.Count; i++)
                    {
                        PdfFigure figure = manager.Figures[i];
                        if (Figures[i].Decorative)
                            figure.IsDecorative = true;          // screen readers skip it
                        else
                            figure.AlternateText = Figures[i].AlternateText;
                    }

                    // save the document with the descriptions
                    byte[] pdf = manager.Save();

                    // return resulted pdf document
                    FileResult fileResult = new FileContentResult(pdf, "application/pdf");
                    fileResult.FileDownloadName = "Document.pdf";
                    return fileResult;
                }
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
                return Page();
            }
        }

        private void Load(PdfAccessibilityManager manager, byte[] source)
        {
            if (string.IsNullOrEmpty(TxtPassword))
                manager.Load(source);
            else
                manager.Load(source, TxtPassword);
        }

        // A tagged document with two figures: one described, one not.
        private static byte[] TestDocument()
        {
            PdfDocument doc = new PdfDocument();
            doc.Tagged = true;
            doc.Language = "en-US";
            PdfPage page = doc.AddPage();

            PdfFont font = doc.Fonts.Add(PdfStandardFont.Helvetica);
            font.Size = 20;
            page.Add(new PdfTextElement(50, 50, "Quarterly report", font) { TagType = PdfTagType.Heading1 });

            string imgFile = Path.Combine(Startup.ServerPath, "wwwroot", "images", "logo.png");
            page.Add(new PdfImageElement(50, 100, 200, 60, imgFile) { TagType = PdfTagType.Figure, AlternateText = "SelectPdf logo" });
            page.Add(new PdfImageElement(50, 200, 300, 90, imgFile) { TagType = PdfTagType.Figure });

            byte[] pdf = doc.Save();
            doc.Close();
            return pdf;
        }
    }
}