1 31 package org.pdfbox.examples.pdmodel; 32 33 import org.pdfbox.pdmodel.PDDocument; 34 import org.pdfbox.pdmodel.PDPage; 35 import org.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination; 36 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; 37 import org.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; 38 39 import java.util.List ; 40 41 50 public class CreateBookmarks 51 { 52 private CreateBookmarks() 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 bookmarks to encrypted document." ); 79 System.exit( 1 ); 80 } 81 PDDocumentOutline outline = new PDDocumentOutline(); 82 document.getDocumentCatalog().setDocumentOutline( outline ); 83 PDOutlineItem pagesOutline = new PDOutlineItem(); 84 pagesOutline.setTitle( "All Pages" ); 85 outline.appendChild( pagesOutline ); 86 List pages = document.getDocumentCatalog().getAllPages(); 87 for( int i=0; i<pages.size(); i++ ) 88 { 89 PDPage page = (PDPage)pages.get( i ); 90 PDPageFitWidthDestination dest = new PDPageFitWidthDestination(); 91 dest.setPage( page ); 92 PDOutlineItem bookmark = new PDOutlineItem(); 93 bookmark.setDestination( dest ); 94 bookmark.setTitle( "Page " + (i+1) ); 95 pagesOutline.appendChild( bookmark ); 96 } 97 pagesOutline.openNode(); 98 outline.openNode(); 99 100 document.save( args[1] ); 101 } 102 finally 103 { 104 if( document != null ) 105 { 106 document.close(); 107 } 108 } 109 } 110 } 111 112 115 private static void usage() 116 { 117 System.err.println( "Usage: java org.pdfbox.examples.pdmodel.CreateBookmarks <input-pdf> <output-pdf>" ); 118 } 119 } | Popular Tags |