Java tutorial
/* * This example was written by Bruno Lowagie, author of the book * 'iText in Action' by Manning Publications (ISBN: 1932394796). * You can use this example as inspiration for your own applications. * The following license applies: * http://www.1t3xt.com/about/copyright/index.php?page=MIT */ package questions.stamppages; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Map; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfAction; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.pdf.SimpleBookmark; public class BookmarksToTOC2 { public static final String RESOURCE = "resources/questions/txt/caesar.txt"; public static final String RESULT = "results/questions/stamppages/bookmarks2toc2.pdf"; @SuppressWarnings("unchecked") public static void main(String[] args) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); writer.setPageEvent(new ParagraphBookmarkEvents(true)); document.open(); BufferedReader reader = new BufferedReader(new FileReader(RESOURCE)); String line; Paragraph p; while ((line = reader.readLine()) != null) { p = new Paragraph(line); p.setAlignment(Element.ALIGN_JUSTIFIED); document.add(p); document.add(Chunk.NEWLINE); } reader.close(); document.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } try { PdfReader reader = new PdfReader(baos.toByteArray()); Rectangle rect = reader.getPageSizeWithRotation(1); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); stamper.insertPage(1, rect); ColumnText column = new ColumnText(stamper.getOverContent(1)); column.setSimpleColumn(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36)); column.addElement(new Paragraph("TABLE OF CONTENTS")); List<Map> list = SimpleBookmark.getBookmark(reader); Chunk link; String dest; for (Map<String, String> bookmark : list) { link = new Chunk(bookmark.get("Title")); dest = bookmark.get("Named"); link.setAction(PdfAction.gotoLocalPage(dest, false)); column.addElement(new Paragraph(link)); } column.go(); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } }