1 31 package org.pdfbox.examples.pdmodel; 32 33 import org.pdfbox.pdmodel.PDDocument; 34 import org.pdfbox.pdmodel.interactive.action.type.PDActionGoTo; 35 import org.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination; 36 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; 37 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; 38 39 import java.io.IOException ; 40 import java.util.List ; 41 42 50 public class GoToSecondBookmarkOnOpen 51 { 52 private GoToSecondBookmarkOnOpen() 53 { 54 } 56 57 64 public static void main( String [] args ) throws Exception 65 { 66 if( args.length != 2 ) 67 { 68 usage(); 69 } 70 else 71 { 72 PDDocument document = null; 73 try 74 { 75 document = PDDocument.load( args[0] ); 76 if( document.isEncrypted() ) 77 { 78 System.err.println( "Error: Cannot add bookmark destination to encrypted documents." ); 79 System.exit( 1 ); 80 } 81 82 List pages = document.getDocumentCatalog().getAllPages(); 83 if( pages.size() < 2 ) 84 { 85 throw new IOException ( "Error: The PDF must have at least 2 pages."); 86 } 87 PDDocumentOutline bookmarks = document.getDocumentCatalog().getDocumentOutline(); 88 if( bookmarks == null ) 89 { 90 throw new IOException ( "Error: The PDF does not contain any bookmarks" ); 91 } 92 PDOutlineItem item = bookmarks.getFirstChild().getNextSibling(); 93 PDDestination dest = item.getDestination(); 94 PDActionGoTo action = new PDActionGoTo(); 95 action.setDestination(dest); 96 document.getDocumentCatalog().setOpenAction(action); 97 98 document.save( args[1] ); 99 } 100 finally 101 { 102 if( document != null ) 103 { 104 document.close(); 105 } 106 } 107 } 108 } 109 110 113 private static void usage() 114 { 115 System.err.println( "Usage: java org.pdfbox.examples.pdmodel.CreateBookmarks <input-pdf> <output-pdf>" ); 116 } 117 } | Popular Tags |