Java Tutorial/PDF/Embedded Javascript
Creates a PDF file that prints after opening
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class MainClass {
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
document.open();
writer.addJavaScript("this.print(false);", false);
document.add(new Paragraph("iText"));
document.close();
}
}
PdfAction javaScript
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfOutline;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.SimpleBookmark;
import com.lowagie.text.pdf.SimpleNamedDestination;
public class MainClass {
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
document.open();
document.add(new Chunk("asdf").setLocalDestination("Title"));
PdfContentByte cb = writer.getDirectContent();
PdfOutline root = cb.getRootOutline();
PdfOutline links = new PdfOutline(root, new PdfAction(), "Useful links");
links.setOpen(false);
new PdfOutline(links, new PdfAction("http://www.jexp.ru"), "jexp.ru");
PdfAction chained = PdfAction.javaScript("app.alert("alert");\r", writer);
chained.next(new PdfAction("http://www.jexp.ru"));
document.close();
PdfReader reader = new PdfReader("2.pdf");
List list = SimpleBookmark.getBookmark(reader);
SimpleBookmark.exportToXML(list, new FileOutputStream(
"outline_actions1.xml"), "ISO8859-1", true);
HashMap map = SimpleNamedDestination.getNamedDestination(reader,
false);
SimpleNamedDestination.exportToXML(map, new FileOutputStream(
"outline_actions2.xml"), "ISO8859-1", true);
}
}