Skip to content

Instantly share code, notes, and snippets.

@notdodo
Last active October 18, 2024 17:35
Show Gist options
  • Save notdodo/a441f2bdfc8c99c1999db0a3e8495fb6 to your computer and use it in GitHub Desktop.
Save notdodo/a441f2bdfc8c99c1999db0a3e8495fb6 to your computer and use it in GitHub Desktop.
Add embedded JavaScript script to a PDF document (python3)
#!/usr/bin/env python3
# https://gist.github.com/edoz90/a441f2bdfc8c99c1999db0a3e8495fb6
# Author: notdodo
try:
from PyPDF2 import PdfFileWriter, PdfFileReader
import click
except ModuleNotFoundError:
print("pip install pypdf2 click")
import sys
sys.exit(-1)
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
def main(javascriptfile, inputpdf, outputpdf):
outputwriter = PdfFileWriter()
inputwriter = PdfFileReader(open(inputpdf, "rb"))
# Read javascript
with open(javascriptfile, "r") as jf:
javascript = jf.read()
# Recreate the stream from the original file
for p in range(inputwriter.getNumPages()):
outputwriter.addPage(inputwriter.getPage(p - 1))
# Add JavaScript
outputwriter.addJS(javascript)
# Write the injected PDF file
outputstream = open(outputpdf, "wb")
outputwriter.write(outputstream)
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option(
"--javascriptfile",
"-jf",
nargs=1,
help="File to embed",
type=click.Path(exists=True, readable=True),
)
@click.argument(
"inputpdf", nargs=1, type=click.Path(exists=True, readable=True)
)
@click.argument("outputpdf", nargs=1, type=click.Path(writable=True))
def cmd(javascriptfile, inputpdf, outputpdf):
"""Add embedded JavaScript to a PDF document that will
execute automatically when the document is opened
Example:\n
app.alert("Hello World!");
Reference: https://adobe.ly/2DtYoYL"""
main(javascriptfile, inputpdf, outputpdf)
if __name__ == "__main__":
cmd()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment