This tutorial describes how to create bookmarks in PDF using Java. It has all the details to set the environment, programming steps, and a sample code to add a bookmark in PDF with Java. You will learn to add bookmarks for all the pages, set display properties of the bookmark, and set a bookmark for a single page.
Steps to Bookmark PDF Document using Java
- Set the environment to use Aspose.PDF for Java to insert a bookmark
- Create an instance of the PdfBookmarkEditor class that supports adding bookmarks
- Bind the PDF with the editor to edit it
- Create an array of titles and a list of pages for defining bookmarks
- Invoke the createBookmarkOfPage() method using the title and pages array
- Save the resultant PDF file with bookmarks in it
Follow these steps to add bookmarks to PDF using Java. You may instantiate the PdfBookmarkEditor object that can bind the source PDF, create bookmarks for the list of pages, and save the resultant PDF. Provide the array of titles and page indexes to the createBookmarkOfPage() method for creating bookmarks.
Code to Insert Bookmark in PDF using Java
// Import the required classes from Aspose.PDF for Java | |
import com.aspose.pdf.facades.PdfBookmarkEditor; | |
import com.aspose.pdf.*; | |
public class Main | |
{ | |
public static void main(String[] args) throws Exception { | |
// Apply the license for Aspose.PDF | |
new License().setLicense("license.lic"); | |
try (PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor()) { | |
bookmarkEditor.bindPdf("SampleDocument.pdf"); | |
// Define bookmark labels for specific sections | |
String[] sectionTitles = { "Overview", "Details", "Summary" }; | |
// Specify the corresponding page numbers for each bookmark | |
int[] sectionPages = { 2, 5, 8 }; | |
// Add bookmarks to the defined pages | |
bookmarkEditor.createBookmarkOfPage(sectionTitles, sectionPages); | |
bookmarkEditor.save("UpdatedDocumentWithBookmarks.pdf"); | |
} catch (Exception ex) { | |
// Handle any errors during the process | |
System.out.println("Error processing the PDF: " + ex.getMessage()); | |
} | |
} | |
} |
This code demonstrates how to bookmark a PDF using Java. You can add bookmarks for all the pages of a PDF using the createBookmarkOfPage() by setting the bookmark name and page index. For setting the bookmark format, call the createBookmarks() with color, bold flag, and Italic flag. The createBookmarkOfPage() can be used to create a bookmark for a particular page by passing the bookmark name and page index.
This article has taught us how to bookmark a PDF. To convert an HTML to an Excel file, refer to the article on how to convert HTML to Excel using Java.