PDF Technique 18

Specifying the document title using the Title entry in the document information dictionary of a PDF document

This is a fairly easy one. The com.itextpdf.text.Document object has an addTitle(String title) method. Use it to set the title. You
should also instruct the screen reader to announce the title by calling PdfWriter.setViewerPreferences(PdfWriter.DisplayDocTitle);.
Here is some sample code:

package ca.discotek.itext.guide;

import java.io.*;

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

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

public class Pdf18Title {
  
  
  public static void main(String[] args) {
    try {
      Document document = new Document(PageSize.LETTER);
      document.addTitle("Some Random Title");
      
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
          "pdf-output/Pdf18Title.pdf"));
      writer.setViewerPreferences(PdfWriter.DisplayDocTitle);

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

      document.open();

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

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

      cb.beginMarkedContentSequence(paragraphElement);

      cb.beginText();

      cb.setFontAndSize(bf, 12);
      cb.setLeading(18);

      cb.moveText(rect.getLeft() + 50, rect.getTop() - 50);

      cb.showText("Some random sentence...");
      cb.endText();

      cb.endMarkedContentSequence();
      
      
      document.close();

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

}

The only relevant lines are 17 and 21. The rest is just filler to create a PDF.

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>