We are again checking the details against your new comments. Can you please confirm if you have tried 25.11 version of the API?
We request that you please try with 25.11 version of the API. If your license doesn’t support this version, you can please obtain a free 30-days temporary license and use it to test with the latest version.
using Aspose.Pdf;
using Aspose.Pdf.Actions;
using System.Collections.Generic;
public class PdfJsExtractor
{
public static List<JavascriptAction> CollectAllJavascript(Document pdf)
{
var jsList = new List<JavascriptAction>();
// 1. Document‑level named JavaScripts (JavaScript dictionary)
if (pdf.JavaScript != null && pdf.JavaScript.Count > 0)
{
foreach (string name in pdf.JavaScript.Keys)
{
// The dictionary stores the script as a plain string, not a JavascriptAction.
// If you need to treat it uniformly, wrap it in a dummy JavascriptAction.
var dummy = new JavascriptAction(pdf.JavaScript[name]);
jsList.Add(dummy);
}
}
// 2. Document‑level actions collection
DocumentActionCollection docActs = pdf.Actions;
AddIfJs(docActs?.BeforeSaving, jsList);
AddIfJs(docActs?.AfterSaving, jsList);
AddIfJs(docActs?.BeforePrinting, jsList);
AddIfJs(docActs?.AfterPrinting, jsList);
AddIfJs(docActs?.BeforeClosing, jsList);
AddIfJs(docActs?.AfterClosing, jsList);
// OpenAction (can be a JavascriptAction)
if (pdf.OpenAction is JavascriptAction openJs)
jsList.Add(openJs);
// 3. Page‑level actions and annotation actions
foreach (Page page in pdf.Pages)
{
// Page actions (OnOpen, OnClose)
if (page.Actions?.OnOpen is JavascriptAction pageOpen)
jsList.Add(pageOpen);
if (page.Actions?.OnClose is JavascriptAction pageClose)
jsList.Add(pageClose);
// Annotation actions
foreach (Annotation annot in page.Annotations)
{
foreach (PdfAction act in annot.PdfActions)
{
if (act is JavascriptAction jsAct)
jsList.Add(jsAct);
}
}
}
return jsList;
}
private static void AddIfJs(PdfAction act, List<JavascriptAction> list)
{
if (act is JavascriptAction js)
list.Add(js);
}
// Example usage
public static void ExtractOrStrip(string inputPath, string outputPath, bool strip)
{
// Load a fresh Document for each file – no shared static state.
var pdf = new Document(inputPath);
var allJs = CollectAllJavascript(pdf);
foreach (var js in allJs)
{
// The script text (for named scripts we wrapped a dummy action)
string script = js.Script;
Console.WriteLine($"Found JavaScript: {script}\n");
if (strip)
js.Script = string.Empty; // or null – both remove the payload
}
if (strip)
pdf.Save(outputPath); // saved PDF no longer contains the scripts
}
}
Key points in the code
CollectAllJavascript gathers scripts from every possible location.
Named JavaScripts are wrapped in a temporary JavascriptAction so the rest of the pipeline can treat them uniformly.
The strip flag demonstrates how to remove the script (js.Script = string.Empty).
A new Document instance is created for each file, eliminating the inter‑mixing problem.
Additional recommendations
Upgrade to the latest Aspose.PDF version – earlier releases had bugs where some action collections returned null even when a script existed.
Process files sequentially or use separate temporary file names if you must work in parallel; never reuse the same temp file (PreFacadeTmp.pdf).
Log the source (document‑level, page‑level, annotation) for each script you find – this helps debugging and compliance reporting.
If you only need the raw JavaScript strings (no need to modify the PDF), you can stop after the Console.WriteLine part and skip the pdf.Save call.
What to do next
Replace the old PdfJavaScriptStripper workflow with the ExtractOrStrip method above.
Verify on a few PDFs that contain:
Named JavaScripts (e.g., /JavaScript << /JS (alert('hi')) >>).
Document actions (/OpenAction).
Page actions (/AA << /O << /S /JavaScript /JS (… ) >> >>).
If any script is still missing, enable Aspose.PDF logging (PdfDocumentInfo.SetLogLevel(LogLevel.Debug)) to see which objects are being parsed.
Report any remaining gaps to Aspose support, providing the PDF sample and the Aspose.PDF version you are using.
:warning: I could not fully verify this explanation against the retrieved sources. Please double-check the behaviour in your environment and confirm the exact SDK/version.
SDK version unclear — refer to the official release notes before applying this guidance.
Reply
vivekk930703
Nov 17
private void processJsActions(List<JavascriptAction> jsActionsList, CleaningResponse response, Boolean shouldExtract) {
Long startTime,endTime;
for (JavascriptAction jsAction : jsActionsList) {
startTime = System.nanoTime();
if (jsAction == null) {
logger.info("Javascript-action is empty");
continue;
}
if (shouldExtract) {
try {
// Setting the script to null effectively removes the malicious payload.
jsAction.setScript(null);
} catch (Exception e) {
logger.warning("Failed to set script: " + e.getMessage());
}
response.setPartResult(SanitizablePart.JavaScript, PartResult.Extracted);
} else {
response.setPartResult(SanitizablePart.JavaScript, PartResult.Analyzed);
}
endTime = System.nanoTime();
response.SetExecutionTime(SanitizablePart.JavaScript, (endTime - startTime));
}
}
private void collectPageAndAnnotationActions(Document doc, List<JavascriptAction> jsActionsList) {
for (Page page : doc.getPages()) {
// Check Page actions (OnOpen, OnClose)
if (page.getActions() != null) {
if (page.getActions().getOnOpen() instanceof JavascriptAction) {
jsActionsList.add((JavascriptAction) page.getActions().getOnOpen());
}
if (page.getActions().getOnClose() instanceof JavascriptAction) {
jsActionsList.add((JavascriptAction) page.getActions().getOnClose());
}
}
for (Annotation annotation : page.getAnnotations()) {
for (PdfAction action : annotation.getPdfActions()) {
if (action instanceof JavascriptAction) {
jsActionsList.add((JavascriptAction) action);
}
}
}
}
}
private void collectNamedDocumentScripts(Document doc, List<JavascriptAction> jsActionsList) {
// Iterate through the keys (script names) in the JavaScript collection
for (String scriptName : doc.getJavaScript().getKeys()) {
String scriptContent = doc.getJavaScript().get_Item(scriptName);
if (scriptContent != null && !scriptContent.isEmpty()) {
logger.info("Found named document JavaScript: " + scriptName);
}
}
}
private void collectDocumentActions(Document doc, List<JavascriptAction> jsActionsList) {
DocumentActionCollection docActions = doc.getActions();
List<PdfAction> actions = Stream.of(docActions.getBeforeSaving(),
docActions.getAfterSaving(),
docActions.getBeforePrinting(),
docActions.getAfterPrinting(),
docActions.getBeforeClosing()) // Added BeforeClosing
.filter(Objects::nonNull)
.collect(Collectors.toList());
IAppointment openAction = doc.getOpenAction();
if (openAction instanceof PdfAction) {
actions.add((PdfAction) openAction);
}
for (PdfAction action : actions) {
if (action instanceof JavascriptAction) {
jsActionsList.add((JavascriptAction) action);
}
}
}
public void handleJavaScript(Document doc, CleaningResponse response, Boolean shouldExtract) {
List<JavascriptAction> allJsActions = new ArrayList<>();
//Collect Document-Level JavaScript Actions (Actions collection and OpenAction)
collectDocumentActions(doc, allJsActions);
//Collect Document-Level Named JavaScripts (JavaScript dictionary)
collectNamedDocumentScripts(doc, allJsActions);
//Collect Page-Level Actions and Annotation Actions
collectPageAndAnnotationActions(doc, allJsActions);
// Process the collected JavaScript actions
if (allJsActions.isEmpty()) {
logger.info("No Embeded javascript found ");
return;
}
processJsActions(allJsActions, response, shouldExtract);
}
what’s wrong in this way ?
Reply
vivekk930703
Nov 17
Whatever the recommendation is, I am already using it in that way, but it still does not detect the JavaScript. You can check it by running it against the attachment.
I have used Aspose PDF 23.8 and 24.12 — the problem exists in both versions.(am i missing something ?)
Reply
asad.ali
Nov 18
@vivekk930703
We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.
Issue ID(s): PDFJAVA-45636
You can obtain Paid Support Services 1 if you need support on a priority basis, along with the direct access to our Paid Support management team.
Reply
vivekk930703
Nov 18
Can you confirm one thing? Do you believe this is an issue that will be fixed under PDFJAVA-45636, or do you think I am using it in the wrong way?
Reply
asad.ali
Nov 18
@vivekk930703
The purpose of the ticket is to investigate why API is not able to detect JavaScript in newer version when it was working before. It is to analyze whether this can be resolved as a bug or using some workaround. We will perform investigation and keep you posted with the status of its rectification. Please be patient and spare us some time.
We are sorry for the inconvenience.
1 Reply
Reply
vivekk930703
27d
The purpose of the ticket is to investigate why API is not able to detect JavaScript in newer version when it was working before. It is to analyze whether this can be resolved as a bug or using some workaround. We will perform investigation and keep you posted with the status of its rectification. Please be patient and spare us some time.
Can you provide some update ?
Reply
asad.ali
27d
@vivekk930703
The ticket has recently been logged in our issue tracking system and will be prioritized on first-come, first-served basis. Once we make progress towards its resolution, we will update you via this forum thread. Please be patient and spare us some time.
We are sorry for the inconvenience.
Reply
vivekk930703
21d
its been week , any update @asad.ali
Reply
asad.ali
21d
@vivekk930703
We are afraid that the ticket is not fully investigated yet due to other issues in the queue. As soon as we have certain updates regarding its resolution, we will inform you. Please spare us some time.
We apologize for the inconvenience.
Reply
vivekk930703
16d
@asad.ali ,
Is there anything you can update us about ?
Reply
asad.ali
16d
@vivekk930703
Regretfully, the ticket hasn’t been yet investigated completely. Once we have some certain news about ticket resolution, we will definitely share with you.
Reply
vivekk930703
10d
@asad.ali ,
Can you please update us ??
Reply
asad.ali
10d
@vivekk930703
We are afraid that the earlier logged ticket hasn’t been resolved due to other pending issues in the queue. As soon as the ticket is scheduled for fix, we will surely inform you via this forum thread. We are sorry for the inconvenience.
Reply
last visit
Share
Bookmark
Flag
Reply
You will receive notifications because you created this topic.
Issues Status
PDFJAVA-45636 ---- Status : Feedback
Suggested Topics
Topic Replies Views Activity
“Fontconfig head is null”, even java.awt.headless=true
Aspose.PDF Product Family
aspose-pdf-java
0 5 16m
Problems with adding Arial Unicode MS to the FontRepository to display chinese characters
Aspose.PDF Product Family
aspose-pdf-java
4 9 2h
Blank PDF while converion from HTML(Email Body)
Aspose.PDF Product Family
aspose-pdf-java
8 27 7h
Client-Side UI Solutions for PDF Editing with AsposePDF on the Back-End
Aspose.PDF Product Family
aspose-pdf-net
javascript
pdf-javascript
1 34 1d
Python 直接读取html问题
中文技术支持
words-python
10 32 10m
There is 1 unread and 23 new topics remaining, or browse other topics in
Aspose.PDF Product Family
Unable to extract javaScript actions from PDF
We do not want to use PdfJavaScriptStripper() at all. The reason is that even with the latest version, the problem will remain the same. When our code is executed at scale, the temporary file name and path are the same for all files if multiple files are received at the same time. Therefore, we do not want to proceed with this approach. The root cause is that the file path and name are identical for all files when they are processed in parallel.
I am following the new approach suggested in your documentation, as mentioned above. This task has been raised solely to seek help with the new approach. However, in the new approach, not all JavaScript actions are being detected. I have attached a few sample files previously for reference.
I hope this time we receive a meaningful update from your end.
Thanks for sharing further details. The ticket status has been changed to Open again. Please allow us to continue our investigation and spare us some time while we get back to you with some feedback. We apologize for the inconvenience caused.
Sadly, no updates are available yet. We are investigating the ticket and will inform you once we have results.
Hi can we get an update please, as this is a paid support ticket now
We are afraid that it has not been yet resolved. The ticket priority has been already raised to the highest priority. We will let you know once significant updates are available in this regard.
HI any update please? does any one working on it? ETA
We are afraid that the investigation is still underway. Once it is completed and we have some ETA, we will inform you.
Any update? it’s was two weeks alreday
Sadly, there is no update yet. Please note that the issue already has the highest priority and we are actively working on it. As soon as our investigation is completed, we will inform you. Your patience and comprehension is highly appreciated in this regard.
We apologize for the inconvenience caused.
I would like to escalate the issue!
This has been on a paid ticket for over three weeks without any meaningful updates.
This is a security issue as we see it, the core product, and we need an update on where we stand.
We do understand your concerns and ensure you that your ticket has been being worked on actively. Since it has already been raised to the priority support, you can obtain updates regarding this ticket from respective paid support thread. We will surely gather further updates about it and share in this forum thread as soon as we have it.
what’s the update now ?
We have already raised your concerns internally and respective paid support team is already gathering updates regarding the ticket investigation status. As of now, we are afraid that no significant updates are available. However, we assure you that you will be notified about the ticket status in respective paid support ticket as soon as updates are gathered.
To remove the action in this specific document (using the second code snippet), the collectPageAndAnnotationActions method can be updated as follows:
for (Annotation annotation : page.getAnnotations()) {
if (annotation instanceof WidgetAnnotation) {
System.out.println("Available annotation class: " + annotation.getClass());
WidgetAnnotation field = (WidgetAnnotation) annotation;
if (field.getAnnotationActions() != null) {
field.getAnnotationActions().removeActions();
}
}
}
This will remove annotation-level actions for WidgetAnnotation objects in the document.
However, for a more universal and reliable solution, we still recommend using the first code snippet. To make the solution thread-safe, we recommend one of the following approaches.
Option 1: Use Streams Instead of Temporary Files (Recommended)
This approach avoids temporary files entirely and processes the document in memory:
Path outputPath = Paths.get(request.GetOutputPath());
try (InputStream in = Files.newInputStream(outputPath);
ByteArrayOutputStream tempOut = new ByteArrayOutputStream()) {
PdfJavaScriptStripper stripper = new PdfJavaScriptStripper();
stripper.strip(in, tempOut);
Files.write(outputPath,
tempOut.toByteArray(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
} catch (Exception e) {
logger.warning("Facade processing failed: " + e.getMessage());
}
Advantages:
- No filename collisions
- No file overwriting between threads
- No content intermixing
- No temporary file cleanup required
- Fully thread-safe
Option 2: Use Unique Temporary Files
If file-based processing is required, use Java’s built-in temporary file creation instead of a hardcoded filename.
Path tempFile = null;
try {
// Create a unique temporary file
tempFile = Files.createTempFile("PreFacadeTmp_", ".pdf");
// Copy original output to temp file
Files.copy(Paths.get(request.GetOutputPath()),
tempFile,
StandardCopyOption.REPLACE_EXISTING);
PdfJavaScriptStripper stripper = new PdfJavaScriptStripper();
stripper.strip(tempFile.toString(), request.GetOutputPath());
} catch (Exception e) {
logger.warning("Facade processing failed: " + e.getMessage());
} finally {
try {
if (tempFile != null) {
Files.deleteIfExists(tempFile);
}
} catch (Exception e) {
logger.warning("Temp file deletion failed.");
}
}
Important Notes
Files.createTempFile() creates the file in the system temporary directory.
On Linux, this is typically /tmp
On Windows, it is usually something like C:\Users<username>\AppData\Local\Temp
The file is NOT deleted automatically. It must be explicitly removed (as shown in the finally block), otherwise it will remain on disk until cleaned manually or by OS-level maintenance.
Files.createTempFile() generates unique filenames such as:
PreFacadeTmp_183746283746.pdf
PreFacadeTmp_918273645111.pdf
Each request receives its own isolated file.
Advantages:
- No collision
- No overwrite
- No intermixing
- Thread-safe behavior
The first solution looks promising, as I have already tried Solution 2 using unique files, but it did not serve our purpose. Let me test this solution, and I will let you know if I notice any issues.