Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsGenerate the PDF first, keep your JavaScript in a Python string, then attach that string as a PDF JavaScript action. ReportLab is a practical way to create the document and AcroForm fields; pypdf can add document-level JavaScript afterward with add_js(javascript: str). The script is not executable merely because it appears in page text or an HTML template.
The complete workflow is: create and save the PDF, reopen it with a PDF library that exposes JavaScript actions, add the script, write a new file, and test that file in the PDF viewers and security environments used by your audience.
The correct execution model
PDF JavaScript belongs to an action dictionary. The PDF specification defines a JavaScript action with S=JavaScript and a JS value containing the source as a text string or stream. Your Python string must become that JS payload.
That distinction explains two common failed approaches:
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
- Drawing
app.alert('Hello')with ReportLab only paints characters on the page; it does not create an action. - Putting a script tag in HTML passed to an HTML-to-PDF renderer does not automatically provide a browser JavaScript runtime.
For a Python-generated interactive PDF, use ReportLab for the document and form widgets, then use pypdf to attach the open-document action.
Install the libraries
Use a virtual environment and install the two libraries:
python -m venv .venv
. .venv/bin/activate
python -m pip install reportlab pypdf
The example below creates a one-page form, saves an intermediate file, and then adds JavaScript that runs when the final PDF opens.
Complete runnable example
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from pypdf import PdfReader, PdfWriter
BASE_PDF = 'form_base.pdf'
FINAL_PDF = 'form_with_javascript.pdf'
# 1. Create the PDF and its AcroForm field.
c = canvas.Canvas(BASE_PDF, pagesize=letter)
width, height = letter
c.setTitle('JavaScript form example')
c.setFont('Helvetica-Bold', 16)
c.drawString(72, height - 72, 'Contact form')
c.setFont('Helvetica', 11)
c.drawString(72, height - 112, 'Name:')
c.acroform.textfield(
name='name',
tooltip='Your name',
x=130,
y=height - 125,
width=300,
height=22,
borderStyle='inset',
borderWidth=1,
forceBorder=True,
fontName='Helvetica',
fontSize=11,
)
c.drawString(72, height - 165, 'This form demonstrates a document-level PDF action.')
c.save()
# 2. Keep the JavaScript source in a Python string.
js = """if (this.getField('name').value === '') {
app.alert('Please enter your name.');
} else {
app.alert('Hello, ' + this.getField('name').value + '!');
}"""
# 3. Attach the string as JavaScript and write a new PDF.
reader = PdfReader(BASE_PDF)
writer = PdfWriter()
writer.append(reader)
writer.add_js(js)
with open(FINAL_PDF, 'wb') as output:
writer.write(output)
print(f'Wrote {FINAL_PDF}')
Run it with python make_pdf.py. Open form_with_javascript.pdf in a desktop PDF viewer that permits document JavaScript. The viewer should display the alert, and the form field remains an AcroForm field that can be read by the script.
Free tools Windows power users keep installed
One-click scans. No signup required.
What each stage does
ReportLab creates the document
canvas.Canvas writes the page and c.acroform.textfield creates a named widget. ReportLab supports text fields, checkboxes, radio buttons, and choice/list controls, but its own interactive-PDF support covers only a fraction of the full PDF standard. If you need an action or form feature that ReportLab does not expose, generate the base file first and add that feature in a post-processing step.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
The Python string is the source, not the action
The variable js is ordinary Python data until it is passed to writer.add_js(js). Keeping it as a triple-quoted string makes multiline scripts readable. Use JavaScript syntax understood by the target PDF viewer; browser-only APIs such as window, document, and fetch are not a safe assumption in PDF JavaScript.
pypdf adds the open action
add_js attaches document-level JavaScript that launches when the PDF is opened. It does not convert arbitrary text into executable code and it does not guarantee that a viewer will run the action. The final file must be written after the action is attached; reopening the intermediate file will not show the new behavior.
Adding other form logic
Name every field you intend to access and use this.getField('fieldName') in the script. For example, a calculation can read two numeric fields and write a result:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
js = """var quantity = Number(this.getField('quantity').value);
var price = Number(this.getField('price').value);
if (isNaN(quantity) || isNaN(price)) {
app.alert('Enter numbers in both fields.');
} else {
this.getField('total').value = (quantity * price).toFixed(2);
}"""
Create the corresponding quantity, price, and total widgets in ReportLab before attaching this script. A field name typo typically produces a null field object, so validate names carefully.
Can WeasyPrint execute JavaScript?
WeasyPrint provides an HTML/CSS path such as HTML(string=...).write_pdf(...) and can optionally produce PDF forms. Its documented rendering path is not a browser-style JavaScript runtime, so do not rely on it to execute arbitrary JavaScript while converting HTML. If your HTML needs JavaScript to calculate content, run that logic before conversion, use a browser automation renderer designed for JavaScript, or attach PDF JavaScript afterward with a PDF post-processor.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Treat untrusted HTML and CSS as a security concern in any server-side conversion service. Sanitise input and isolate the renderer according to your deployment policy.
Viewer support and security settings
The PDF standard specifies how a conforming processor should execute a JavaScript action, but it does not make every viewer behave identically. Desktop viewers may show a trust prompt, disable document scripts globally, or restrict APIs. Browser PDF plug-ins and mobile viewers often expose a smaller feature set.
- Test the exact final file, not only the intermediate ReportLab output.
- Test the viewers your recipients actually use, including any managed enterprise configuration.
- Provide a non-script fallback, such as visible instructions or server-side validation, when the workflow is important.
- Do not place secrets, access tokens, or destructive operations in document JavaScript. A recipient can inspect the PDF and its script.
Troubleshooting
No alert appears
Confirm that you opened the post-processed file and that the viewer allows document JavaScript. Try a trusted desktop viewer, check its preference for PDF JavaScript, and inspect any security prompt. If scripts are disabled by policy, the Python code cannot override that policy.
The script is visible but does not run
If the text appears on the page, it was drawn as page content rather than attached with add_js. Keep the source in a Python string and pass that exact string to the PDF action API.
getField returns nothing
Use the exact field name passed to ReportLab’s textfield or another widget method. Duplicate or hierarchical names can also make field lookup confusing; use unique, simple names while debugging.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
The output PDF is damaged
Write to a new output path, close the input file before replacing it, and ensure the process has permission to write the destination. If your installed pypdf version reports an API difference, consult that version’s PdfWriter documentation and keep the same logical sequence: read, append or clone, add JavaScript, write.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →JavaScript works in one viewer only
That is a compatibility issue, not proof that the Python string was embedded incorrectly. Reduce the script to standard PDF JavaScript APIs, remove browser-specific assumptions, and retain a non-script path.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and deployment notes
For small forms, the extra pypdf pass is usually simpler and more reliable than trying to make the generation library handle every interactive feature. In batch jobs, generate to a temporary file, post-process it, verify that the output exists and has a nonzero size, then move it into place atomically. Keep the JavaScript source under version control alongside the Python code and add a test that checks the expected field names and output file.
Do not assume that adding JavaScript makes a static PDF interactive in every environment. A PDF can contain a valid action while a viewer chooses not to execute it. Document that requirement for users and provide a server-side alternative when compliance, billing, or data integrity depends on the result.
Or skip the browser setup
If your PDF workflow also needs clean screenshots of web pages, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status.
Here is the one-call cURL example (see the ScreenshotNeo API documentation for options):
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. You can sign up for the free plan.
Frequently Asked Questions
Does the JavaScript run when the PDF is printed?
Printing normally renders the page and does not provide a dependable trigger for document-open JavaScript. Perform required calculations before generating the PDF or validate the data on your server.
Can I attach JavaScript without creating AcroForm fields?
Yes. pypdf can attach a document-level script to a PDF that has no form fields, but the script still needs APIs and viewer support that exist in the target PDF application.
Is PDF JavaScript the same as JavaScript in a web browser?
No. PDF viewers expose a separate, restricted JavaScript API. Browser globals and network APIs should not be assumed to exist.
What should I do when recipients use a viewer that blocks scripts?
Generate a usable non-script PDF, expose the same calculation or validation on your application server, and tell recipients which viewer is required for optional interactive behavior.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

