iText library allows you to create PDF, RTF or HTML documents from Java classes at runtime. com.lowagie.text package gives facility to manipulate HTML documents.

The example below shows you how to add javascript code to an HTML file. On loading of the page, an alert will be shown. Clicking to the link will also call show() function.

 import com.lowagie.text.*;
import java.io.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.html.*;
import com.lowagie.text.rtf.*;

class  createDocument
{
  public static void main(String args[])
  {  
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try 
    {
      HtmlWriter pdf = HtmlWriter.getInstance(document, 
        new FileOutputStream("text.html"));

      document.addTitle("Hello World example");

      StringBuffer s = new StringBuffer();
      s.append("\t\tfunction load() {\n");
      s.append("\t\t  alert('Page has been loaded.');\n");
      s.append("\t\t}\n");
      s.append("\t\tfunction show(){\n");
      s.append("\t\t  alert('This is javascript');\n");
      s.append("\t\t}");

      document.add(new Header(HtmlTags.JAVASCRIPT, s.toString()));
      document.setJavaScript_onLoad("load()");
      document.open();
      document.add(new Paragraph("Hello World"));

      Anchor a  = new Anchor("Click");
      a.setReference("javascript:show()");
      document.add(a);

    } 
    
    catch(Exception de) 
    {
      System.err.println(de.getMessage()); 
    } 
    document.close(); 
  }
}