Auto Tag PDF for Accessibility

The PdfTagger class adds tags to an existing PDF document that has none, such as a document produced by an application without accessibility support. The headings, paragraphs, lists, tables, images, captions, footnotes, table of contents entries, links and form fields are found in the pages and written as the structure of the document in reading order, while page headers, page footers and decorations are marked as artifacts. Charts and diagrams can be tagged as figures too. The pages look the same after tagging and the document can be saved as PDF/UA-1 or PDF/UA-2.

The demo application tags a short annual report created without tags. The report has a table of contents, a list, a bar chart, a table and a photo with their captions and a footnote.

Tag a PDF Document

A PdfTagger object loads the document from a memory buffer or from a file, with the password of a protected document as an optional parameter. PdfTaggerAutoTag finds the structure of the document and tags its content and PdfTaggerSave returns the tagged document, while PdfTaggerSaveToFile(String) writes it to a file. AutoTagAsync(CancellationToken), SaveAsync(CancellationToken) and SaveToFileAsync(String, CancellationToken) are the asynchronous versions of these methods.

Tag a PDF Document
// Load the PDF document to tag
using PdfTagger pdfTagger = new PdfTagger("report.pdf");

// Find the structure of the document and tag its content
pdfTagger.AutoTag();

// Save the tagged document to a file
pdfTagger.SaveToFile("report_tagged.pdf");

IsTagged tells if the loaded document is already a tagged PDF. Such a document is left as it is, unless ReplaceExistingTags is set to replace its tags. The analysis of the pages can take up to RunTimeoutSec seconds, 120 by default.

PDF Standard, Language and Title

PdfStandard selects the standard of the tagged document: PdfUa1, the default, PdfUa2, or None for a tagged PDF without a standard identification.

The language of a document that does not declare one is found from its text, with en-US used when it cannot be found, and the title of a document without a title is taken from its first heading. Language and Title set them instead, as a language code such as en-US and as a text.

When a standard is set, the standard fonts the document uses without embedding them are replaced by embedded fonts and the text keeps its position on the page. The other fonts the document uses without embedding them are embedded when they are installed on the system. KeepStandardFonts leaves all these fonts as they are and PdfFontManagerSetStandardFontSubstitute(PdfStandardFont, PdfBaseFont) sets the font that replaces a standard font.

Set the PDF Standard, the Language and the Title
// Write the tagged document as PDF/UA-2
pdfTagger.PdfStandard = PdfStandard.PdfUa2;

// The language and the title, for a document that does not declare them
pdfTagger.Language = "en-US";
pdfTagger.Title = "Annual Review";

Images, Charts and Diagrams

The images are tagged as figures with the alternative text of ImageAlternativeText, which is Image by default. ImagesAsArtifacts marks the images as artifacts, for documents where they are only decorations.

The drawings made of lines and curves, such as charts and diagrams, are marked as artifacts and the text inside them is tagged as text. When DrawingsAsFigures is set to true, they are tagged as figures with the same alternative text.

ImageAlternativeTextProvider is a function that receives each figure as a PdfTaggedImage object, with its page number, its bounds and IsDrawing to tell a drawing from an image, and returns its alternative text. When it returns null or an empty text, the figure keeps the text of ImageAlternativeText.

Set the Alternative Text of the Figures
pdfTagger.ImageAlternativeText = "Illustration";

// Tag the charts and the diagrams as figures
pdfTagger.DrawingsAsFigures = true;

// A text of its own for each chart
pdfTagger.ImageAlternativeTextProvider = figure =>
    figure.IsDrawing ? "Chart on page " + figure.PageNumber : null;

Tables and Bookmarks

The cells of the first row of each table are tagged as header cells, as set by FirstTableRowIsHeader, which is true by default. A document without bookmarks receives a bookmark for each heading found in its pages, unless AddBookmarks is set to false.

Tagging Result

After AutoTag, Result gives the language and the title of the tagged document, the number of headings, paragraphs, lists, tables, captions, footnotes, links and form fields that were tagged, the number of bookmarks added and the figures with the alternative text each one received.

PagesWithoutText lists the pages that show only an image, as scanned pages do, whose text can be tagged after it is recognized, and UntaggedPages the pages whose content could not be read and were left as they were. FontsNotEmbedded and FontsWithoutUnicode list the fonts that PDF/UA requires to be embedded or to have Unicode values for their characters.

Read the Tagging Result
pdfTagger.AutoTag();

PdfTaggingResult result = pdfTagger.Result;
Console.WriteLine($"Headings: {result.Headings}, tables: {result.Tables}, figures: {result.Images.Length}");

// The scanned pages have no text to tag
if (result.PagesWithoutText.Length > 0)
    Console.WriteLine("Pages without text: " + string.Join(", ", result.PagesWithoutText));

Code Sample - Auto Tag PDF for Accessibility

C#
using System;
using System.IO;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EvoPdf_Next_AspNetDemo.Models;
using EvoPdf_Next_AspNetDemo.Models.Tag_PDF;

// Use EVO PDF Namespace
using EvoPdf.Next;

namespace EvoPdf_Next_AspNetDemo.Controllers.Tag_PDF
{
    public class Auto_Tag_PDFController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public Auto_Tag_PDFController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            var model = SetViewModel();

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> TagPdf(Auto_Tag_PDF_ViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the license key received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.LicenseKey = "your-license-key";

            byte[] inputPdfBytes = null;
            string outputFileName = null;

            // If an uploaded file exists, use it with priority
            if (model.PdfFile != null && model.PdfFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.PdfFile.CopyToAsync(ms);
                    inputPdfBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded PDF file", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.PdfFile.FileName) + "_Tagged.pdf";
            }
            else
            {
                // Otherwise, fall back to the URL
                string pdfUrl = model.PdfFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(pdfUrl))
                    throw new Exception("No PDF file provided: upload a file or specify a URL");

                try
                {
                    if (pdfUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
                    {
                        string localPath = new Uri(pdfUrl).LocalPath;
                        inputPdfBytes = await System.IO.File.ReadAllBytesAsync(localPath);
                    }
                    else
                    {
                        using var httpClient = new System.Net.Http.HttpClient();
                        inputPdfBytes = await httpClient.GetByteArrayAsync(pdfUrl);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not download the PDF file from URL", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(new Uri(model.PdfFileUrl).AbsolutePath) + "_Tagged.pdf";
            }

            // Load the PDF document to tag. The password is needed only for a password-protected document
            string password = !string.IsNullOrEmpty(model.Password) ? model.Password : null;
            using PdfTagger pdfTagger = new PdfTagger(inputPdfBytes, password);

            // The PDF standard of the tagged document: PDF/UA-1, PDF/UA-2 or a tagged PDF without a standard
            pdfTagger.PdfStandard = model.PdfStandard == "PdfUa2" ? PdfStandard.PdfUa2 :
                model.PdfStandard == "None" ? PdfStandard.None : PdfStandard.PdfUa1;

            // The language of a document that does not declare one. When it is not set, the language is found
            // from the text of the document
            if (!string.IsNullOrWhiteSpace(model.Language))
                pdfTagger.Language = model.Language.Trim();

            // The title of a document that has no title. When it is not set, the first heading is used
            if (!string.IsNullOrWhiteSpace(model.Title))
                pdfTagger.Title = model.Title.Trim();

            // The alternative text of the images and of the drawings. An application can give each image its own
            // text with the ImageAlternativeTextProvider function
            if (!string.IsNullOrWhiteSpace(model.ImageAlternativeText))
                pdfTagger.ImageAlternativeText = model.ImageAlternativeText.Trim();

            // Mark the images as artifacts instead of figures of the document structure
            pdfTagger.ImagesAsArtifacts = model.ImagesAsArtifacts;

            // Tag the charts and the diagrams made of lines and curves as figures
            pdfTagger.DrawingsAsFigures = model.DrawingsAsFigures;

            // Tag the cells of the first row of each table as header cells
            pdfTagger.FirstTableRowIsHeader = model.FirstTableRowIsHeader;

            // Add a bookmark for each heading to a document without bookmarks
            pdfTagger.AddBookmarks = model.AddBookmarks;

            // Leave the fonts the document uses without embedding them as they are instead of embedding them
            pdfTagger.KeepStandardFonts = model.KeepStandardFonts;

            // Replace the tags of a document that is already tagged
            pdfTagger.ReplaceExistingTags = model.ReplaceExistingTags;

            // Find the structure of the document and tag its content
            pdfTagger.AutoTag();

            // Save the tagged document in a memory buffer
            byte[] outPdfBuffer = pdfTagger.Save();

            // Send the tagged PDF document to the browser as a download
            FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
            fileResult.FileDownloadName = outputFileName;
            return fileResult;
        }

        private Auto_Tag_PDF_ViewModel SetViewModel()
        {
            var model = new Auto_Tag_PDF_ViewModel();

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Auto_Tag_PDF".Length);

            model.PdfFileUrl = rootUrl + "/DemoAppFiles/Input/PDF_Files/Untagged_Report.pdf";

            return model;
        }
    }
}

See Also