DEV Community

Alexis
Alexis

Posted on

Java-How to Add, Read, Modify or Delete Bookmarks in PDF

Bookmarks allow you to jump to a specific point in a PDF file quickly by marking text, pictures, and places. When you operate the PDF file with a large number of pages, you may need to add, read, modify or delete bookmarks in a PDF file programmatically to ensure that it is easy to jump to the location you want. This article will demonstrate how to use Spire.PDF to operate the bookmarks from the following five parts:

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>8.9.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Add Bookmarks in PDF Files in Java

Spire.PDF for java offers PdfDocument.getBookmarks().add() method to add bookmark to the PDF file. Here comes to the details.

  • Create a PdfDocument instance and load the sample PDF using PdfDocument.loadFromFile() method.
  • Loop through the PDF pages and get pages collection in the PDF document using PdfPageBase. getPages().get(i) method.
  • Add bookmarks to PDF using PdfDocument.getBookmarks().add() method
  • Set destination page and location for the bookmark.
  • Set color and text style for the bookmark.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.*;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;
import java.awt.geom.Point2D;

public class addBookmarks {

    public static void main(String[] args) throws Exception {


        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("PDFSample.pdf");

        //Loop through the pages in the PDF file
        for(int i = 0; i< pdf.getPages().getCount();i++) {
            PdfPageBase page = pdf.getPages().get(i);

            //Add bookmark
            PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", i + 1));

            //Set destination page and location
            PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 0));
            bookmark.setAction(new PdfGoToAction(destination));

            //Set text color
            bookmark.setColor(new PdfRGBColor(new Color(139, 69, 19)));

            //Set text style
            bookmark.setDisplayStyle(PdfTextStyle.Bold);


        //Save the result file
        pdf.saveToFile("AddBookmarks.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Add bookmarks

Read Bookmarks from a PDF File in Java

With the help of Spire.PDF for Java, you can get the information of a bookmark like the title or formatting in the PDF bookmarks.

  • Create a PdfDocument instance and load the sample PDF using PdfDocument.loadFromFile() method.
  • Get bookmarks collection in the PDF document using PdfDocument.getBookmarks() method.
  • Get the bookmarks’ content and save to a TXT file using custom method GetBookmarks().
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfBookmarkCollection;

import java.io.FileWriter;
import java.io.IOException;

public class getBookmark {

    public static void main(String[] args) throws Exception {


        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Get bookmarks collection
        PdfBookmarkCollection bookmarks = pdf.getBookmarks();

        String result = "getAllPdfBookmarks.txt";

        GetBookmarks(bookmarks, result);
    }
        private static void GetBookmarks(PdfBookmarkCollection bookmarks, String result) throws IOException {
            //Declare a new StringBuilder content
            StringBuilder content = new StringBuilder();

            //Get Pdf bookmarks information.
            if (bookmarks.getCount() > 0) {
                content.append("Pdf bookmarks:");
                for (int i = 0; i < bookmarks.getCount(); i++) {
                    PdfBookmark parentBookmark = bookmarks.get(i);
                    content.append(parentBookmark.getTitle() + "\r\n");

                    //Get the text style.
                    String textStyle = parentBookmark.getDisplayStyle().toString();
                    content.append(textStyle + "\r\n");
                 }
            }
            writeStringToTxt(content.toString(),result);
        }

    public static void writeStringToTxt(String content, String txtFileName) throws IOException {
        FileWriter fWriter = new FileWriter(txtFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Get all bookmarks

Modify Bookmark Title in PDF file in Java

You can edit the existing bookmarks in a PDF file, for example, change the bookmark title, font color and text display style. Here comes to the steps:

  • Create a PdfDocument instance and load the sample PDF using PdfDocument.loadFromFile() method.
  • Get the first bookmark in the PDF document using PdfDocument.getBookmarks().get(0) method.
  • Set the title for the bookmark using bookmark.setTitle() method.
  • Set the color and display style for the first bookmark.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;


public class editBookmark {

    public static void main(String[] args) throws Exception {


        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Get the first bookmark
        PdfBookmark bookmark = pdf.getBookmarks().get(0);

        //Change the title of the bookmark
        bookmark.setTitle("New Title");

        //Change the font color of the bookmark
        bookmark.setColor(new PdfRGBColor(new Color(255,0,0)));

        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Save the result file
        pdf.saveToFile("EditBookmarks.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Modify bookmarks

Delete a Particular Bookmark in Java

Spire.PDF for java supports to remove a particular bookmark from the PDF.

  • Create a PdfDocument instance and load the sample PDF using PdfDocument.loadFromFile() method.
  • Delete a particular bookmark using PdfDocument.getBookmarks().removeAt() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class deleteBookmark {

    public static void main(String[] args) throws Exception {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load the PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Delete the second bookmark 
        pdf.getBookmarks().removeAt(1);

        //Save the result file
        pdf.saveToFile("DeleteBookmark.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Remove a particular bookmark

Delete all Bookmarks in a PDF File in Java

Spire.PDF for java offers PdfDocument.getBookmarks().clear() method to remove all the bookmarks from the PDF file.

  • Create a PdfDocument instance and load the sample PDF using PdfDocument.loadFromFile() method.
  • Remove all bookmarks using PdfDocument.getBookmarks().clear() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class deleteAllbookmarks {

    public static void main(String[] args) throws Exception {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load the PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Delete all bookmarks
        pdf.getBookmarks().clear();

        //Save the result file
        pdf.saveToFile("DeleteBookmark2.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Clear all bookmarks

Conclusion

In this article, we have demonstrated how to add bookmark to the PDF file, edit an existing pdf bookmark by changing the text and font style and remove the bookmarks from PDF in Java applications. Besides bookmarks, Spire.PDF for java also supports to operate the attachments, annotations, watermarks and other elements on the PDF. You can check the PDF forum for more features to operate the PDF files.

Top comments (0)