Add javasceipt action to a annotation using javascript (programmatically)
1. For the freetext anotations (many in each page) in a pdf , i need to add hyperlink, which will take the name of the freetext annotation content,
2. the hyperling on mouseclick should run a javascript action, that has to open another pdf at the named location
3. The "namedlocation" title is same as the freetext content in the original pdf.
ChatGPT code is attached, which mostly works.. but is not able to add the javascript action to the hyperlink
// Step 1: Initialize an array to keep track of processed free text contents
var processedContents = [];
// Step 2: Iterate through each page in the PDF
for (var pageNum = 0; pageNum < this.numPages; pageNum++) {
// Step 3: Search for annotations on the page
var annots = this.getAnnots({ nPage: pageNum });
if (annots) {
for (var i = 0; i < annots.length; i++) {
var annot = annots[i];
if (annot.type === "FreeText" && annot.author === "CONTROL VALVE") {
var dest = annot.contents; // Named destination
var externalPDF = "C:/Users/LENOVO/OneDrive - KBR/Desktop/DESTINATIOn.pdf"; // Updated file path
// Check if the content has already been processed
if (processedContents.indexOf(dest) === -1) {
processedContents.push(dest);
// Step 4: Create a hyperlink around the free text annotation
var linkRect = annot.rect;
var link = this.addLink(pageNum, linkRect, {
borderColor: color.blue, // Set border color to blue
borderWidth: 1, // Set border width to 1 point
});
// Step 5: Set the link's appearance properties (optional)
link.textSize = 12; // Set the text size
link.textFont = font.Helvetica; // Set the font
link.textColor = color.blue;
link.fillColor = color.transparent;
link.text = "Link Text"; // Set the link text
// Step 6: Create the custom JavaScript for the "Run a JavaScript" action
var javascriptContent = `
app.openDoc('${externalPDF}', {
page: 0,
zoom: 'fitpage',
dest: '${dest}'
});
`;
// Step 7: Set the "Run a JavaScript" action for Mouse Up event
var action = link.setAction("MouseUp", javascriptContent);
}
}
}
}
}
