We have a use case where we need to map bookmarks to the page numbers where the corresponding text can be found. Our current code allows us to navigate to the exact page number, but it doesn’t precisely locate the text associated with the bookmark. We want to enhance this feature so that when a user clicks on a bookmark or outline item, they are taken not only to the correct page but also directly to the specific text the bookmark refers to.
static String addHighlightsToPDF(String pdfPath,String JsonPath) {
String fullPath="/tmp/output_aspose.pdf";
try {
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("/tmp/"+pdfPath);
// Delete all bookmarks
pdfDocument.getOutlines().delete();
// Iterate through the pages
for(Page singlePage : pdfDocument.getPages())
{
// Iterate through the annotations
for(Annotation singleAnnot : singlePage.getAnnotations())
{
singlePage.getAnnotations().delete(singleAnnot);
}
}
FileReader reader = new FileReader("/tmp/"+JsonPath);
JSONTokener tokener = new JSONTokener(reader);
JSONObject object = new JSONObject(tokener);
JSONArray keys = object.names ();
JSONArray jsonArray = object.getJSONArray("text_reference");
// Iterate jsonArray using for loop
for (int i = 0; i < jsonArray.length(); i++) {
OutlineItemCollection pdfOutline = new OutlineItemCollection(pdfDocument.getOutlines());
JSONObject explrObject = jsonArray.getJSONObject(i);
if(!explrObject.isNull("reference_text") && !explrObject.isNull("reference_page")){
// Split the paragraph into words.
String[] words = ((String) explrObject.get("reference_text")).split(" ");
String comment = words.toString();
if(words.length>6){
// Get the first three words.
String[] firstThreeWords = Arrays.copyOfRange(words, 0, 3);
// Get the last three words.
String[] lastThreeWords = Arrays.copyOfRange(words, words.length - 3, words.length);
comment=String.join(" ",firstThreeWords)+" ... "+String.join(" ",lastThreeWords);
}
pdfOutline.setTitle("REF_BIN_"+(String) explrObject.get("id")+"_"+comment);
pdfOutline.setAction(new GoToAction(pdfDocument.getPages().get_Item(Integer.parseInt((String) explrObject.get("reference_page")))));
// Add a bookmark in the document's outline collection.
// not adding outline to avoid bookmarks mismatch problem
pdfDocument.getOutlines().add(pdfOutline);
...