PDF Technique 13

Providing replacement text using the /Alt entry for links in PDF documents

This technique just builds on PDF11. You will see how the /Alt entry is applied between lines 47 and 53.

package ca.discotek.itext.guide;

import java.io.*;
import java.net.URL;

import ca.discotek.itext.DocumentStructure;
import ca.discotek.itext.DocumentStructure.PageStructure;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class Pdf13AltLink {
  
  public static void main(String[] args) {
    try {
      Document document = new Document(PageSize.LETTER);
      
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
          "pdf-output/Pdf13AltLink.pdf"));

      Rectangle rect = document.getPageSize();
      
      writer.setTagged();

      document.open();

      PdfContentByte cb = writer.getDirectContent();
      PdfStructureTreeRoot rootElement = writer.getStructureTreeRoot();

      DocumentStructure documentStructure = new DocumentStructure(rootElement, "en-ca"); // for english canadian
      PageStructure pageStructure = documentStructure.getPage(0);
      PdfStructureElement paragraphElement = new PdfStructureElement(pageStructure.bodyElement, PdfName.P);

      float llx = 50; 
      float lly = rect.getTop() - 200; 
      float urx = 300; 
      float ury = rect.getTop() - 100; 
      ColumnText ct = new ColumnText(cb); 
      ct.setSimpleColumn(llx, lly, urx, ury); 
      Chunk chunk = new Chunk("Web Site for iText WCAG 2.0 PDF Information"); 
      PdfAction action = new PdfAction(new URL("https://discotek.ca")); 
      chunk.setAction(action);
      ct.addText(chunk);  
      PdfStructureElement linkElement = new PdfStructureElement(paragraphElement, PdfName.LINK); 
      cb.beginMarkedContentSequence(new PdfStructureElement(linkElement, PdfName.OBJR)); 
      
      PdfDictionary dict = new PdfDictionary();
      dict.put(PdfName.ALT, new PdfString("This link goes to discotek.ca, provides information about how to implement WCAG 2.0 with itext."));
      cb.beginMarkedContentSequence(PdfName.SPAN, dict, true);
      
      ct.go(); 
      
      cb.endMarkedContentSequence(); // span/alt 
      cb.endMarkedContentSequence(); // link element

      document.close();
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>