Wednesday, 12 August 2020

Add, Edit, Read and Delete Bookmarks in a PDF Document in Java

It is very useful to add bookmarks to PDF files, especially technical documents and instruction manuals. After you add bookmarks to a PDF file, you can access to a specific part of a PDF file easily and efficiently. In this article, I’ll show you how to add, edit, read and delete bookmarks in a PDF document by using Free Spire.PDF for Java.

Dependency

First of all, please download the latest version of Free Spire.PDF for Java from the link, and add Spire.Pdf.jar to your project as a dependency.

Of course, if you are using maven, you can directly add the following code to your project’s pom.xml file.

<repositories> 

        <repository> 

            <id>com.e-iceblue</id> 

            <name>e-iceblue</name> 

            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url> 

        </repository> 

</repositories> 

<dependencies> 

    <dependency> 

        <groupId>e-iceblue</groupId> 

        <artifactId>spire.pdf.free</artifactId> 

        <version>2.6.3</version> 

    </dependency> 

</dependencies>

Add Bookmarks

The first step of adding bookmarks is to loop through all pages in a PDF file, and then add bookmarks and childbookmarks for each page. At the same time, you can set text color and style for bookmarks by using setColor and setDisplayStyle methods.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
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 AddBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Load a PDF file
       
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.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, 50));
            bookmark.setAction(
new PdfGoToAction(destination));
           
//Set text color
           
bookmark.setColor(new PdfRGBColor(new Color(139, 7, 126)));
           
//Set text style
           
bookmark.setDisplayStyle(PdfTextStyle.Bold);

           
//Add child bookmark
           
PdfBookmark childBookmark = bookmark.add(String.format("ChildBookmark-%s", i + 1));
           
//Set destination page and location
           
PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 200));
            childBookmark.setAction(
new PdfGoToAction(childDestination));
           
//Set text color
           
childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
           
//Set text style
           
childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }
       
//Save the result file
       
pdf.saveToFile("output/AddBookmarks.pdf");
    }
}

Output

Edit Bookmarks

Using setTitle, setColor and setDisplayStyle methods, you can change the title, color and style of bookmarks 
and childbookmarks in a PDF file.
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) {
       
//Create a PdfDocument instance
       
PdfDocument doc = new PdfDocument();
       
//Load the PDF file
       
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");
       
//Get the first bookmark
       
PdfBookmark bookmark = doc.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(2, 139, 2)));
       
//Change the outline text style of the bookmark
       
bookmark.setDisplayStyle(PdfTextStyle.Italic);
       
//Edit child bookmarks of the first bookmark
       
for (PdfBookmark childBookmark : (Iterable <PdfBookmark>) bookmark) {
            childBookmark.setColor(
new PdfRGBColor(new Color(255, 19, 24)));
            childBookmark.setDisplayStyle(PdfTextStyle.
Bold);
        }
       
//Save the result file
       
doc.saveToFile("output/EditBookmarks.pdf");
        doc.close();
    }
    }

Output

Read Bookmarks

To read bookmarks in a PDF file, you first get the bookmark collection by using pdf.getBookmarks() method,
and then create a .txt file and insert bookmarks in it.
import com.spire.pdf.*;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfBookmarkCollection;
import java.io.FileWriter;
import java.io.IOException;
public class ReadBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Load the PDF file
      
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");
       
//Get bookmarkCollection
       
PdfBookmarkCollection bookmarkCollection = pdf.getBookmarks();
       
//Crate a StringBuilder instance
       
StringBuilder stringbuilder = new StringBuilder();
       
//Define a method to get bookmarks
       
GetBookmarkTitle(bookmarkCollection, stringbuilder);
       
//Create a .txt file,and write down bookmarks
       
FileWriter writer;
       
try {
            writer =
new FileWriter("output/ReadBookmark.txt");
            writer.write(stringbuilder.toString());
            writer.flush();
        }
catch (IOException e) {
            e.printStackTrace();
        }
        pdf.dispose();
    }
   
// Define a method to get the titles of bookmarks
   
static void GetBookmarkTitle(PdfBookmarkCollection bookmarkCollection, StringBuilder stringbuilder)
    {
       
if (bookmarkCollection.getCount()> 0)
        {
           
for(int i = 0 ; i< bookmarkCollection.getCount(); i++ )
            {
                PdfBookmark parentBookmark = bookmarkCollection.get(i);
                stringbuilder.append(parentBookmark.getTitle());
                GetBookmarkTitle(parentBookmark, stringbuilder);
            }
        }
    }
}

Output

Delete Bookmarks

You can easily delete a specific child bookmark, a parent bookmark along with its child bookmarks or all the bookmarks from a PDF file.

import com.spire.pdf.PdfDocument;
public class DeleteBookmark {

public static void main(String[] args) {
//Create a PdfDocument instance

PdfDocument pdf = new PdfDocument();

//Load the PDF file
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");

//Delete the first child bookmark

//pdf.getBookmarks().get(0).removeAt(0);

//Delete the first bookmark along with its child bookmark
//pdf.getBookmarks().removeAt(0);

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

//Save the result file

pdf.saveToFile("output/DeleteBookmarks.pdf");
    }
}





No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...