> ## Documentation Index
> Fetch the complete documentation index at: https://developers.gonitro.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Redact text you searched for

> Find text in a PDF with the Text Bounding Boxes method and redact every match with the Redact method of the Nitro API.

A common flow is "find this text, then redact it": search a PDF with the
[Text Bounding Boxes](https://developers.gonitro.com/docs/api-reference/platform/extractions/text-box.md) method, then pass the boxes it
found to the [Redact](https://developers.gonitro.com/docs/api-reference/platform/transformations/redact.md) method.

The boxes the search returns already have what Redact needs — a zero-based `pageIndex` and a
`boundingBox` as `[x, y, width, height]` in points (see the [Bounding Box Guide](https://developers.gonitro.com/docs/build-nitro/bounding-box.md)).
But they are nested inside the search result, and Redact expects one flat `redactions` list, so the
search result can't be sent to Redact as it is. Doing so is rejected with a `422` error.

## From search result to redactions

The search result groups boxes by query, then by match:

```json theme={null}
{
  "result": {
    "textBoxes": [
      {
        "query": { "text": "John Doe", "isRegex": false, "regexFlags": [] },
        "matches": [
          {
            "matchedText": "John Doe",
            "boxes": [
              { "pageIndex": 0, "boundingBox": [50.25, 57.08, 62.53, 15.64], "textPiece": "John Doe" }
            ],
            "groups": []
          },
          {
            "matchedText": "John Doe",
            "boxes": [
              { "pageIndex": 0, "boundingBox": [75.0, 87.83, 62.53, 15.64], "textPiece": "John Doe" }
            ],
            "groups": []
          }
        ]
      }
    ]
  }
}
```

To turn it into Redact parameters:

1. Take every box from `textBoxes[].matches[].boxes[]`, across all queries and all matches. A match
   that spans several lines has one box per line, so keep them all.
2. Keep each box's `pageIndex` and `boundingBox`. You can add a `label` if you want text drawn on the
   redaction box.
3. Ignore `groups`. Their boxes cover parts of the match, which the match's own boxes already cover.
4. Send the list as `{"redactions": [...]}`.

For the result above, the Redact parameters are:

```json theme={null}
{
  "redactions": [
    { "pageIndex": 0, "boundingBox": [50.25, 57.08, 62.53, 15.64] },
    { "pageIndex": 0, "boundingBox": [75.0, 87.83, 62.53, 15.64] }
  ]
}
```

> [!NOTE]
>
> The search result is under `result` in a JSON response and in an asynchronous job's result. When you
> download the result as a file (`Accept: application/octet-stream`), `textBoxes` is at the top level
> instead. The Python and JavaScript functions below take the object that holds `textBoxes`: pass
> `result` from a JSON response, or the downloaded file's content as it is.

## Examples

Each example removes duplicate boxes. They only occur when two of your queries match the same text,
for example a keyword listed twice, or a literal query and a regular expression that find the same
value. Redact would accept the duplicates, but there is no reason to send them.

```bash curl + jq theme={null}
# 1. Search the PDF
curl -s https://api.gonitro.dev/extractions \
  -H "Authorization: Bearer $TOKEN" \
  -F method=text-bounding-boxes \
  -F 'params={"queries":[{"text":"John Doe"},{"text":"\\d{3}-\\d{2}-\\d{4}","isRegex":true}]}' \
  -F file=@input.pdf > search.json

# 2. Collect the boxes into Redact parameters
#    (.result // .) reads .result from a JSON response, or the top level of a downloaded result file
jq -c '{redactions: ([(.result // .).textBoxes[].matches[].boxes[] | {pageIndex, boundingBox}] | unique)}' \
  search.json > redact-params.json

# 3. Redact the same PDF
curl -s https://api.gonitro.dev/transformations \
  -H "Authorization: Bearer $TOKEN" \
  -H "Accept: application/octet-stream" \
  -F method=redact \
  -F "params=$(cat redact-params.json)" \
  -F file=@input.pdf -o redacted.pdf
```

```python Python theme={null}
import json
from typing import TypedDict

BoundingBox = tuple[float, float, float, float]  # x, y, width, height, in points


class Box(TypedDict):
    pageIndex: int
    boundingBox: list[float]
    textPiece: str


class Match(TypedDict):
    matchedText: str
    boxes: list[Box]


class QueryResult(TypedDict):
    matches: list[Match]


class TextBoxesResult(TypedDict):
    textBoxes: list[QueryResult]


class Redaction(TypedDict):
    pageIndex: int
    boundingBox: BoundingBox


def search_result_to_redactions(search_result: TextBoxesResult) -> list[Redaction]:
    """Collect the boxes of a Text Bounding Boxes result into Redact's `redactions`."""
    seen: set[tuple[int, BoundingBox]] = set()
    redactions: list[Redaction] = []
    for query_result in search_result["textBoxes"]:
        for match in query_result["matches"]:
            for box in match["boxes"]:  # not match["groups"]
                x, y, width, height = box["boundingBox"]
                key = (box["pageIndex"], (x, y, width, height))
                if key in seen:  # two queries matched the same text
                    continue
                seen.add(key)
                redactions.append({"pageIndex": key[0], "boundingBox": key[1]})
    return redactions


# A JSON response has the search result under "result".
# For a downloaded result file, pass its parsed content instead.
redactions = search_result_to_redactions(search_response["result"])
if redactions:
    params = json.dumps({"redactions": redactions})  # the Redact method's params
```

```javascript JavaScript theme={null}
/**
 * Collect the boxes of a Text Bounding Boxes result into Redact's `redactions`.
 * @param {{ textBoxes: { matches: { boxes: { pageIndex: number, boundingBox: [number, number, number, number] }[] }[] }[] }} searchResult
 * @returns {{ pageIndex: number, boundingBox: [number, number, number, number] }[]}
 */
function searchResultToRedactions(searchResult) {
  const seen = new Set();
  const redactions = [];
  for (const queryResult of searchResult.textBoxes) {
    for (const match of queryResult.matches) {
      for (const box of match.boxes) { // not match.groups
        const key = JSON.stringify([box.pageIndex, box.boundingBox]);
        if (seen.has(key)) continue; // two queries matched the same text
        seen.add(key);
        redactions.push({ pageIndex: box.pageIndex, boundingBox: box.boundingBox });
      }
    }
  }
  return redactions;
}

// A JSON response has the search result under `result`.
// For a downloaded result file, pass its parsed content instead.
const redactions = searchResultToRedactions(searchResponse.result);
if (redactions.length > 0) {
  // send JSON.stringify({ redactions }) as the Redact method's params
}
```

If the search found nothing, the list is empty: skip the Redact call and keep the original file.

## Power Automate

In Power Automate, **Extract searched Text from PDF** returns the nested result, and **Redact PDF
Pages** takes the redactions as two lists, **Redaction Pages** and **Redaction Boxes**, matched by
position. To connect them:

**1. Collect the boxes**

Add **Initialize variable** with name `boxes` and type **Array**. Then nest three **Apply to
each** loops:

* over `body('Extract_searched_Text_from_PDF')?['result']?['textBoxes']`
* inside it, over `items('Apply_to_each')?['matches']`
* inside that, over `items('Apply_to_each_2')?['boxes']`

In the innermost loop, add **Append to array variable** `boxes` with the value
`items('Apply_to_each_3')`.

**2. Build Redaction Pages**

Add a **Select** with **From** `variables('boxes')`. Switch **Map** to text mode and enter
`item()?['pageIndex']`. Set **Redaction Pages** on **Redact PDF Pages** to
`join(body('Select'), ',')`.

**3. Build Redaction Boxes**

Add a second **Select** with **From** `variables('boxes')`. Switch **Map** to text mode and
enter `join(item()?['boundingBox'], ',')`. Set **Redaction Boxes** on **Redact PDF Pages** to
`join(body('Select_2'), ';')`.

**4. Skip empty results**

Put **Redact PDF Pages** inside a **Condition** that checks `length(variables('boxes'))` is
greater than `0`, so a search with no matches doesn't call Redact with empty lists.

Action names in the expressions (`Apply_to_each_2`, `Select_2`, …) must match the names in your
flow. If two of your queries can match the same text, the lists may contain the same box twice.
Redact accepts that, so there is no need to remove them in a flow.

In Zapier, **Text Bounding Box Extract From PDF** already returns a flat **Redactions JSON** field
you can map straight into **Redact PDF** — see
[Working with files](https://developers.gonitro.com/docs/integrations/zapier/working-with-files.md#chaining-actions).

## Good to know

* **Redacting only part of a match.** For a regular expression with capture groups, each match
  also has `groups`, each with its own `boxes`. To redact only the captured part, such as the amount
  in `Total: \$(\d+\.\d{2})`, take the boxes from `matches[].groups[].boxes[]` instead of
  `matches[].boxes[]`.
* **Labels.** If you add a `label`, don't use `matchedText` or `textPiece` for it: the label is
  drawn on the redaction box, so it would print the redacted text back onto the page.
* **Overlapping queries.** A shorter query inside a longer one (`Doe` and `John Doe`) returns a
  smaller box inside the bigger one. Both are kept, which is harmless.
* **Matching rules.** Literal queries are case-sensitive. To match regardless of case, use a regular
  expression with the `ignore-case` flag — see
  [Text Bounding Boxes](https://developers.gonitro.com/docs/api-reference/platform/extractions/text-box.md).
* **Text split across lines.** A literal query such as `John Doe` doesn't match when the line breaks
  between `John` and `Doe`. To catch those too, use a regular expression with `\s` between the
  words (`John\sDoe`); the match then has one box per line, and the steps above redact both.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.