1 31 package org.pdfbox.examples.pdmodel; 32 33 import org.pdfbox.exceptions.InvalidPasswordException; 34 35 import org.pdfbox.pdfparser.PDFParser; 36 37 import org.pdfbox.pdmodel.PDDocument; 38 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; 39 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; 40 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode; 41 42 import java.io.FileInputStream ; 43 import java.io.IOException ; 44 45 53 public class PrintBookmarks 54 { 55 62 public static void main( String [] args ) throws Exception 63 { 64 if( args.length != 1 ) 65 { 66 usage(); 67 } 68 else 69 { 70 PDDocument document = null; 71 FileInputStream file = null; 72 try 73 { 74 file = new FileInputStream ( args[0] ); 75 PDFParser parser = new PDFParser( file ); 76 parser.parse(); 77 document = parser.getPDDocument(); 78 if( document.isEncrypted() ) 79 { 80 try 81 { 82 document.decrypt( "" ); 83 } 84 catch( InvalidPasswordException e ) 85 { 86 System.err.println( "Error: Document is encrypted with a password." ); 87 System.exit( 1 ); 88 } 89 } 90 PrintBookmarks meta = new PrintBookmarks(); 91 PDDocumentOutline outline = document.getDocumentCatalog().getDocumentOutline(); 92 if( outline != null ) 93 { 94 meta.printBookmark( outline, "" ); 95 } 96 else 97 { 98 System.out.println( "This document does not contain any bookmarks" ); 99 } 100 } 101 finally 102 { 103 if( file != null ) 104 { 105 file.close(); 106 } 107 if( document != null ) 108 { 109 document.close(); 110 } 111 } 112 } 113 } 114 115 118 private static void usage() 119 { 120 System.err.println( "Usage: java org.pdfbox.examples.pdmodel.PrintBookmarks <input-pdf>" ); 121 } 122 123 131 public void printBookmark( PDOutlineNode bookmark, String indentation ) throws IOException 132 { 133 PDOutlineItem current = bookmark.getFirstChild(); 134 while( current != null ) 135 { 136 System.out.println( indentation + current.getTitle() ); 137 printBookmark( current, indentation + " " ); 138 current = current.getNextSibling(); 139 } 140 141 } 142 } | Popular Tags |