Pdf SimpleBookmark : Bookmarks « PDF « Java Tutorial






import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfContentByte;
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 MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();
    Paragraph hello = new Paragraph("asdf");
    Chapter universe = new Chapter("A", 1);
    Section section;
    section = universe.addSection("B");
    section.add(hello);
    section = universe.addSection("C");
    section.add(hello);
    document.close();
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    PdfReader reader = new PdfReader("2.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
        "HelloWorldManipulateBookmarks.pdf"));
    stamper.insertPage(1, PageSize.A4);
    PdfContentByte cb = stamper.getOverContent(1);
    cb.beginText();
    cb.setFontAndSize(bf, 18);
    cb.setTextMatrix(36, 770);
    cb.showText("Inserted Title Page");
    cb.endText();
    stamper.addAnnotation(PdfAnnotation.createText(stamper.getWriter(), new Rectangle(30f, 750f,
        80f, 800f), "inserted page", "This page is the title page.", true, null), 1);
    List list = SimpleBookmark.getBookmark(reader);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("Title", "Title Page");
    ArrayList kids = new ArrayList();
    HashMap<String, String> kid1 = new HashMap<String, String>();
    kid1.put("Title", "top");
    kid1.put("Action", "GoTo");
    kid1.put("Page", "1 ");
    kids.add(kid1);
    HashMap<String, String> kid2 = new HashMap<String, String>();
    kid2.put("Title", "bottom");
    kid2.put("Action", "GoTo");
    kid2.put("Page", "6");
    kids.add(kid2);
    map.put("Kids", kids);
    list.add(0, map);
    SimpleBookmark.exportToXML(list, new FileOutputStream("manipulated_bookmarks.xml"),
        "ISO8859-1", true);
    stamper.setOutlines(list);
    stamper.close();
  }
}








29.33.Bookmarks
29.33.1.Add bookmark
29.33.2.Read PDF File to retrieve the bookmarks
29.33.3.Set bookmark title
29.33.4.Pdf SimpleBookmark
29.33.5.Copy book mark