I'm using Netbeans and the iText pdf api. So I have the following method that creates a hashtable that can be inserted into a pdf. In this case they are image files that are to be placed in the pdf at the end of the document.
private HashMap<String, Object> newTmp = new HashMap<>(); //to generate bookmarks from images, another object is made
private ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<>(); //an array list is instantiated for bookmarks to be saved
private void bookmarkGen(String imageList[]) {
int n = 0; //counter used to progress each bookmark.
for (int i = 0; i < imageList.length; i++) {
if (imageList[i] != null) {
bookmarks.add(newTmp);
newTmp.put("Title", imageList[i].substring(imageList[i].lastIndexOf("/"), imageList[i].lastIndexOf(".")));
newTmp.put("Action", "GoTo");
newTmp.put("Page", String.format("%d Fit", n++));
System.out.print(n + "\n");
System.out.print("Bookmark Added\n");
}
}
}
The next part of this process involves the following lines of code to input the bookmarks to the pdf.
if (!bookmarks.isEmpty() && pdfcounter > 0) {
copy.setOutlines(bookmarks);
System.out.println("Bookmarks have been outlined");
}
Whenever I do this, one of the bookmarks just go to one page and the rest don't have a page assigned. What am I doing wrong?
You create newTmp
once and add it to your list multiple times, overwriting its entries each time. Thus, you eventually have a list containing many references to newTmp
with the values set in the last iteration of the loop.
To fix this, move
private HashMap<String, Object> newTmp = new HashMap<>();
Into the loop.