Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add high-level API for adding document JavaScripts #643

Merged
merged 8 commits into from
Oct 31, 2020
23 changes: 23 additions & 0 deletions src/api/PDFDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,29 @@ export default class PDFDocument {
return copiedPages;
}

/**
* Add document JavaScript. The script is executed when the document is opened.
* See the [JavaScript™ for Acrobat® API Reference](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf)
* for details.
* @param script The JavaScript to execute.
* @param name The name of the script. Must be unique per document.
*/
brodo marked this conversation as resolved.
Show resolved Hide resolved
addJavascript(script: string, name: string) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we alter the implementation of this method a bit? There are some existing patterns in the codebase that should be followed. Please see https://github.com/Hopding/pdf-lib/blob/master/src/api/PDFEmbeddedFile.ts#L48. File embedding is similar to JavaScript embedding in some respects.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've taken the code you suggested and adopted it. It's way better this way...

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I'll try to review it again tomorrow evening.

const jsActionDict = this.context.obj({
Type: 'Action',
S: 'JavaScript',
JS: PDFHexString.fromText(script),
});
const jsActionRef = this.context.register(jsActionDict);
const jsNameTree = this.context.obj({
Names: this.context.obj([name, jsActionRef]),
});
this.catalog.set(
Hopding marked this conversation as resolved.
Show resolved Hide resolved
PDFName.of('Names'),
this.context.obj({ JavaScript: jsNameTree }),
);
}

/**
* Add an attachment to this document. Attachments are visible in the
* "Attachments" panel of Adobe Acrobat and some other PDF readers. Any
Expand Down