Scripting: How to add annotation to PDF?

I’d like to add a highlight annotation to a PDF with a (JavaScript) script. The code seems to run ok (i.e. there are no errors reported, and the last console.log shows that the file has one annotation with reasonable width/height. However, neither DT nor Preview show any highlight.

How the script works:

  • It finds a PDF containing the string searchString (Q2957) in a particular DT group
  • It then uses findStringWithOptions from PDFKit to find all occurrences of the search string in this PDF document (there’s only one)
  • It figures out the page in the PDF where the string is located (pdfPage)
  • It then gets the bounding box for the string on this page
  • It creates a highlight annotation with this bounding box, setting its color to green and the markupType to “highlight” (0).
  • Finally, it adds the annotation to the page. Where it never seems to arrive, although
  • in the last step, the script outputs the number of annotations on this page, their type and bounding box. The output looks ok to me (1 annotation, type is “Highlight”, and it has a reasonable bounding box).

I know that this is not DT related, but perhaps someone has an idea what I’m doing wrong anyway …

ObjC.import('PDFKit');
ObjC.import('AppKit');
ObjC.import('Foundation');
(() => {
const app = Application("DEVONthink 3");
const searchString = 'Q2957';
app.includeStandardAdditions = true;
const searchGroup = app.createLocation('/Kontoauszüge/ING', {in: app.databases['ck Privat']});
const foundFiles = app.search(`text:${searchString}`,{in: searchGroup});
if (foundFiles.length === 1) {
  const path = foundFiles[0].path();
  const pdfDoc = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath($(path)));
  const pdfSelections = pdfDoc.findStringWithOptions($(searchString),null);
  if(pdfSelections.js.length === 1) {
    const selection = pdfSelections.js[0];
    const pdfPage  = selection.pages.js[0]; /* PDFPage object, not a number! */
    const bounds = selection.boundsForPage(pdfPage);
    const annotation = $.PDFAnnotation.alloc.initWithBoundsForTypeWithProperties(bounds, $.PDFAnnotationSubtypeHighlight, {});
    annotation.color=$.NSColor.greenColor;
    annotation.markupType = 0;
    annotation.shouldDisplay = true;
    pdfPage.addAnnotation(annotation);
    pdfPage.displaysAnnotations = true;
    const annotationsOnPage = pdfPage.annotations;
    console.log(`${annotationsOnPage.js.length} annotations found on page ${pdfPage.label.js}
    height: ${$.NSHeight(annotationsOnPage.js[0].bounds)}, width:${$.NSWidth(annotationsOnPage.js[0].bounds)} `)
  }
}
})()

The changes are not saved back to disc.

Indeed – that’s it. pdfDoc.writeToFile() did the trick. Thanks a lot!

2 Likes