Package: inject-javascript
Inject JavaScriptInject JavaScript within PDF document body:arrow_up: Top of Document:building_construction: Requirements:zap: Quick Start🗒 Notes:card_index: Attribution:balance_scale: LicensingRequirementsNote, the following steps arenotrequired if installing this project via Pip.Python version 3 based dependencies may be installed via one of the following methods...Scoped within current user...pip3install--user-rrequirements.txtScoped with aVirtual Environmentlocal to the directory of this project...pip3install--userpipenv

pipenvinstall-rrequirements.txtNote, reviewPython Guide --virtualenvsfor more information on Python Virtual Environments.Or scopped for the entire system...sudopip3install-rrequirements.txtNote, generally installing dependencies system-wide isnotrecommended.Quick StartInstall this project via Pippip3install--user--upgradeinject-javascriptExamples of running as command-line utilityPrint available options and exitinject-pdf-javascript--helpInject.jsinto.pdfand save to.pdfinject-pdf-javascript--jsindex.js\--pdfdocument.pdf\--save-pathenhanced.pdf\--escapeInject.jsinto.pdfand overwrite.pdfinject-pdf-javascript--jsindex.js\--pdfdocument.pdf\--escape\--clobberExample of inheriting and modifying theInject_JavaScriptclass...#!/usr/bin/env python3fromargparseimportArgumentParserfrominject_javascriptimportInject_JavaScriptfrominject_javascript.libimporterrorclassCustomized_Inject_JavaScript(Inject_JavaScript):"""Customizes Inject_JavaScript class"""defreturn_js_data(self,js_path=None):"""Customizes how JavaScript data is processed prior to returning"""js_data=super(Customized_Inject_JavaScript,self).return_js_data(js_path=js_path)returnjs_dataif__main__=='__name__':"""Code that is run if this file is executed as a script instead of imported"""## Command line argument parsing only if being called as a scriptarg_parser=ArgumentParser(prog=basename(argv[0]),usage='%(prog)s--pdf "/tmp/boring.pdf" --js "/dir/script.js"',epilog='For more projects see: https://github.com/S0AndS0')arg_parser.add_argument('--pdf-path','--pdf',help='Out path to save PDF',required=True)arg_parser.add_argument('--js-path','--js',help='JavaScript to inject into downloaded PDF',required=True)arg_parser.add_argument('--save-path',help='Path to save enhanced PDF to, ignored if clobber is True')arg_parser.add_argument('--escape',help='Prevent replacing/escaping of specific character combos',action='store_true',default=False)arg_parser.add_argument('--clobber',help='Overwrite preexisting/input PDF',action='store_true',default=False)arg_parser.add_argument('--verbose','-v',help='Loudness of this script',action='count')verbose=arg_parser.parse_known_args()[0].verboseargs=vars(arg_parser.parse_args())## Use provided command line optionsinjector=Customized_inject_javascript(clobber=args.get('clobber'),escape=args.get('escape'),verbose=verbose)injected_path=injector.inject_pdf_with_javascript(pdf_path=args.get('pdf_path'),js_path=args.get('js_path'),save_path=args.get('save_path'))ifverbose>0:print('Enhanced file maybe found at:{0}'.format(injected_path))NotesTheinject_javascript.pyscript currently is limited to injecting JavaScript into the document body of PDF file(s), which means certain APIs arenotavailable such asrequest. Please submit a Pull Request for injecting folder level script features if additional API functionality is desired.The--escapecommand-line option willdouble-downon backslashes (\), for example...if(typeofapp!=='undefined'){varscript_context='pdf';}else{varscript_context='browser';};if(script_context==='pdf'){window.alert('Script context is -> PDF\nExpect features to be limited.');}else{window.alert('Script context is -> Browser\nExpect features to _mostly_ be available.')}... the above code if injected with the--escapeoption would result in the following changes...varscript_context=typeofapp!=='undefined'?'pdf':'browser';if(script_context==='pdf'){window.alert('Script context is -> PDF\\nExpect features to be limited.');}else{window.alert('Script context is -> Browser\\nExpect features to _mostly_ be available.')}... while the default behavior ofinject_javascript.pyis tonotadd additional backslashes, generally such modifications are required for JavaScript to run properly within PDF(s).Adobe Acrobat PDF readers as of last documentation checks run JavaScript based on version 1.5 of ISO-16262 (ECMA-262 Edition 3 from December 1999), meaning that some newer ECMA Script features may not be available, thus it may be a good idea to utilize a JavaScript transpiler such as TypeScript.tsconfig.json{"compilerOptions":{"target":"es3","module":"none","lib":["dom","es5"],"locale":"en-US","noImplicitAny":false,"sourceMap":true,"outDir":"js"},"exclude":["node_modules"],"files":["ts/index.ts"]}Note, above example configurations may transpile JavaScript of a version that is higher than supported by PDF readers of your target audience.ts/index.tslethello=(arg:string)=>{window.alert(`Hello${arg}!`);};hello('world');js/index.jsvarhello=function(arg){window.alert("Hello "+arg+"!");};hello('world');//# sourceMappingURL=index.js.mapAttributionAdobe --JavaScript for AcrobatGitHub --github-utilities/make-readmeMozilla Developer --New in JavaScript 1.5TypeScript --Compiler OptionsYouTube -- Omar Rizwan (@rsnous)LicenseDocumentation for injecting JavaScript within PDF document body
Copyright (C) 2020 S0AndS0

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.For further details review full length version ofAGPL-3.0License.