PDF Technique 11

Providing links and link text using the /Link structure element in PDF documents

This technique will ensure that a screen reader will identify the linked content as a link before reading the content. Here is an example:

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 Pdf11Link {
  
  public static void main(String[] args) {
    try {
      Document document = new Document(PageSize.LETTER);
      
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
          "pdf-output/Pdf11Link.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)); 
      ct.go(); 
      cb.endMarkedContentSequence(); 

      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>