# Run PDF Script

Run JavaScript on a PDF from the document context menu or [Command Palette](Command-Palette.md). Use an included script or edit your own with the same API as [sumatrapdf-tool run](Tool-run.md).

**Available in pre-release 3.7 and SumatraPDF ng desktop builds.**

**Choose a script, check its arguments, then press Run Script.**

- **Arguments:** each row becomes an entry in `scriptArgs`, starting at `scriptArgs[0]`.
- **Input and output:** the first two rows start with the current PDF and an unused output filename beside it.
- **Examples:** load, create, annotate, extract text, render images, merge, create thumbnails, draw graphics, trace rendering, replace JPEG 2000 images, copy an outline, or bake annotations.
- **Results:** stdout and stderr appear below the script after it finishes. A failed script also reports its exit code.

## Run an included script

1. Open a PDF, press `Ctrl + K`, and choose **Run PDF Script...** (`CmdRunPDFScript`). You can also choose it from the document context menu.
2. Choose an example from the drop-down.
3. Check **Arg 1** (input) and **Arg 2** (output). Use **...** to choose a file, **x** to delete a row, or **Add arg** to append one.
4. Press **Run Script**. Open the output file when the script finishes.

Some examples require a third argument: an image for **Create PDF** or **Draw graphics with Device**, another input PDF for **Merge PDFs**, an outline source for **Copy outline**, or a page number for **Trace device** (default: 1).

## Write your own script

The runner supplies MuPDF classes such as `Document`, `PDFDocument`, `Image`, and `Buffer`. Use `print()` to write output. See the [JavaScript API reference](Tool-run-javascript-reference.md).

```js
var doc = Document.openDocument(scriptArgs[0]);
print("Pages:", doc.countPages());
doc.save(scriptArgs[1], "compress");
```

You can also use `"<INPUT>"` and `"<OUTPUT>"` inside the script. They expand to the first two argument values, escaped for a JavaScript string:

```js
var doc = Document.openDocument("<INPUT>");
doc.save("<OUTPUT>", "compress");
```

## Tips

- Changes saved in the viewer are available to the script; unsaved annotations are not, because scripts read the file on disk.
- Choose an output extension that matches the example: **Draw graphics with Device** writes PNG; **Convert PDF to images** appends page numbers and `.png` to the output path.
- The script and arguments remain editable after a run. Selecting another example replaces the script text.
- The command requires disk access and is unavailable in restricted mode without it or in WebAssembly.

## See also

- [JavaScript examples](Tool-run-javascript-examples.md)
- [JavaScript API reference](Tool-run-javascript-reference.md)
- [Command-line runner](Tool-run.md)
