# Logo placement, watermarks and thermal cropping

All dimensions are PDF points: 72 points = 1 inch. The existing API paths, upload field names and old defaults remain available. New geometry controls are opt-in; the browser sends them explicitly when you use the updated placement controls.

## Add a logo: `POST /api/logo/add`

Upload `pdfFile` and optionally `logoImage`. Omitting `logoImage` uses the bundled Shipwave logo. Existing requests that contain only `x`, `y`, `width` and `height` retain their original behavior: raw unrotated PDF coordinates, every page, a 100 × 50 point image at `(100,100)` by default, and no bounds adjustment.

Supplying any of the following fields enables visible-page geometry:

- `position`: `custom`, `center`, `top`, `top-left`, `top-right`, `bottom`, `bottom-left`, `bottom-right`, `left`, or `right`. The default in the new mode is `custom`.
- `rotation`: any angle from `-360` to `360`, default `0`. Positive values rotate **counterclockwise as seen in the preview**. API callers can use `angle` as an alias, but must not supply both names.
- `scale`: uniform multiplier from `0.05` to `10`, default `1`.
- `opacity`: `0` to `1`, default `1`; zero is completely transparent.
- `pages`: `all` or distinct one-based page numbers/ranges, such as `1,3-5`. Default `all`; at most 1000 selected pages. Unselected pages remain present and receive no logo.
- `margin`: inset for anchor positions, default `18` points, range `0–1440`. It does not affect `custom` coordinates.

`width=100` and `height=50` remain the unrotated logo dimensions. Scaling changes both dimensions; rotating then changes the footprint. For example, an 80 × 40 point logo rotated 90° occupies a 40 × 80 point rectangle.

In the new mode, `x` and `y` locate the **bottom-left of that final rotated visual rectangle**, relative to the visible page's bottom-left. They default to `100,100` for `position=custom`. Source page rotation and cropped pages are handled automatically, so the angle and placement correspond to what the preview shows. Anchor positions use the rotated rectangle and the visible CropBox intersected with the MediaBox. Do not send `x` or `y` with an anchor position; use its margin instead. Placements that would leave the visible page are rejected with `400`, rather than silently clipped or moved.

The original PDF filename is retained. Page dimensions and page count remain unchanged; adding a logo does not flatten existing form fields.

```bash
curl "$BASE_URL/api/logo/add" -H "X-API-Key: $API_KEY" \
  -F "pdfFile=@labels.pdf" -F "logoImage=@logo.png" \
  -F "position=top-right" -F "rotation=90" \
  -F "width=80" -F "height=40" -F "margin=18" \
  -F "scale=1" -F "opacity=1" -F "pages=1-3" \
  --output labels-branded.pdf
```

## A4 to thermal: `POST /a4-to-thermal`

The upload field remains `pdf`, and the output filename remains `thermal-label.pdf`.

Requests with **none** of `cropPreset`, `rotation`, `outputOrientation`, `allPages` or `pages` use the original implementation unchanged. Its defaults are `cropX=0`, `cropY=0`, `cropWidth=400`, `cropHeight=600`; it uses the first page, fits into a 288 × 432 point page, and transfers the original page with the historical crop offset formula. This compatibility mode does not add a new exact clipping boundary.

Supplying any new field enables exact crop geometry:

- `cropPreset=custom` is the default. `custom`, `top-half`, `bottom-half`, `left-half`, `right-half` and `full` are accepted.
- The four half-page presets refer to the **viewed visible page**, including its existing rotation. `top-half` always means the upper half you see, even when the source PDF has a 90° rotation. They use the entire chosen half, without guessing the label's position inside it. `full` selects the complete visible page.
- For `custom`, use `cropX`, `cropY`, `cropWidth` and `cropHeight`. Defaults remain `0,0,400,600`. These coordinates are relative to the **unrotated visible page's bottom-left**, before source rotation. Fractional points are supported. The rectangle must fit the visible unrotated area. Raw crop fields do not affect a preset.
- `rotation`: `0`, `90`, `180` or `270`, default `0`. This rotates the selected content **clockwise after cropping**. It is additional to the source page's existing rotation.
- `outputOrientation=portrait` produces 288 × 432 points; `landscape` produces 432 × 288 points. Default `portrait`.
- `allPages=false` is the default and selects only the first page. `true` selects all source pages, up to 100.
- Optional `pages` accepts distinct one-based numbers/ranges, for example `2,1` or `1,3-5`. An explicit selection overrides `allPages`, retains its specified order, and is limited to 100 selected pages.

The selected content is clipped, rotated, then fitted proportionally and centered on the output page. Its aspect ratio is retained; empty space is expected when the crop and output have different proportions. Content from outside the selected region does not appear, apart from possible single-pixel antialiasing at a shared cut boundary. Choose the output orientation independently from which source half contains the label.

The new output is a rebuilt PDF: source form appearances are flattened before embedding, and interactive annotations or links are not retained. Cropping is a print/layout operation; underlying source objects can remain inside embedded page content. Use the actual redaction tool when content must be permanently removed.

```bash
curl "$BASE_URL/a4-to-thermal" -H "X-API-Key: $API_KEY" \
  -F "pdf=@a4-labels.pdf" -F "cropPreset=right-half" \
  -F "rotation=90" -F "outputOrientation=landscape" \
  -F "allPages=true" --output thermal-label.pdf
```

## Watermark geometry: `POST /api/watermark/add-watermark`

Existing defaults and raw placement remain unchanged when `placementMode` is omitted or `legacy`. The existing text, color, opacity, font size, position and rotation fields keep their meanings.

Set `placementMode=visible` to place against the visible page, compensate source rotation, and keep the rotated text footprint inside its anchor. `margin=50` is the default in this mode; it accepts `0–1440` points. Supported positions remain `center`, the four corners, `top-center` and `bottom-center`. Rotation remains `-180–180` degrees, positive counterclockwise. Font metrics and a small horizontal safety allowance keep descenders and accents inside the placement rectangle. A text footprint too large for the page and margin returns `400`.

Optional `pages=all` or a distinct one-based list/range selects up to 1000 pages while retaining all other source pages. Page selection also works with legacy placement. The upload remains `pdfFile`, and the original filename is retained.

```bash
curl "$BASE_URL/api/watermark/add-watermark" -H "X-API-Key: $API_KEY" \
  -F "pdfFile=@document.pdf" -F "watermarkText=COPY" \
  -F "placementMode=visible" -F "position=top-right" \
  -F "rotation=45" -F "margin=24" -F "pages=2-4" \
  --output watermarked.pdf
```

Without an explicit `region` or `placement`, text overlays and the legacy add-text tool keep their documented raw PDF coordinates. They do not acquire implicit rotation, anchor placement or page selection from the logo/watermark controls.

## Direct object frames

Release 4.2 adds the optional multipart `placement` JSON string to `/api/logo/add`, `/add-text` and `/api/watermark/add-watermark`:

```json
{"page":1,"x":100,"y":400,"width":240,"height":100,"rotation":30,"coordinateSpace":"visible"}
```

X/Y locate the **unrotated frame's lower-left corner** in the viewed visible page. Width/height are the unrotated frame dimensions. Positive rotation turns the object counterclockwise about the frame center. All four rotated corners must fit the selected visible page. Source page rotation and CropBox offsets are compensated. Only that one-based source page changes; the other pages remain intact.

Allowed keys are `page/x/y/width/height/rotation/coordinateSpace`. X/Y are finite numbers in `-100000–100000`; a negative origin is valid only when the rotated frame still fits the page. Width/height are `0.01–100000`. Rotation is optional, defaults to zero and accepts `-360–360`. The coordinate space is optional and can only be `visible`. The serialized object is limited to 2048 characters. Numeric strings and unknown keys are rejected.

Logos use the frame's exact width/height. The workspace's corner handles retain proportions; API integrations should preserve them when desired. Text/watermarks embed Liberation Sans and uniformly fit the actual ink bounds into the frame, centered. Frame dimensions determine text size in this mode. The existing legacy and measured-region text fonts and sizing rules are unchanged.

Do not combine `placement` with `region`, raw geometry, separate rotation/angle, anchors, margins, scale or page/page-list fields. Text additionally forbids `size/fontSize`; watermark also forbids `fontSize/size/placementMode`. Explicit conflicts return 400 rather than being ignored. Logo opacity remains available. Placement text supports its existing named colors plus `#RRGGBB` and opacity `0–1`; watermark keeps its hex color and `0.1–1` opacity range.

This frame is distinct from a selected `region`, which bounds the final rotated footprint. Existing raw logo geometry also uses its own final rotated bounding-box origin. Explicitly choose the intended mode rather than reusing the same X/Y with a different name. Omitted `placement` retains existing defaults and region behavior.

The workspace's live handles use this protocol. Dragging and keyboard gestures update a local overlay; Apply creates the PDF result. A retained tool step uses its original input when reapplied, while a new step uses the latest result. Handles do not select arbitrary objects already embedded in the uploaded PDF. Preview frames, rulers, handles and grid lines never appear in the export.

`POST /api/pdf/placement-preview` accepts JSON `{"text":"COPY"}` and returns the embedded font identity and vector ink metrics. The normalized positioned paths have Y increasing upward in font units. Preview clients uniformly fit and center them within the same frame used by the saved PDF. Text is a nonempty supported single line of at most 2000 characters; unknown body keys are rejected. This authenticated metadata route has a 32 KiB body limit, needs no PDF upload and does not reserve processing usage. Cache by text and transform locally while dragging. See the [API guide](API.md#post-apipdfplacement-preview) for response fields.

## Shared measured regions

The preview's rulers/grid and rectangle selection use a common, reusable region:

```json
{"page":1,"x":36,"y":72,"width":144,"height":54,"coordinateSpace":"visible"}
```

`page` is one-based. X/Y locate the selected rectangle's bottom-left in the **visible page as viewed**, after the source page's existing crop and 0/90/180/270-degree rotation. Width and height are positive (at least 0.01). Coordinates are finite raw PDF user-space units, normally points (72/inch). A PDF with `UserUnit=2` has two physical points per raw unit; the browser and API both retain that raw coordinate system. The measurement API reports `userUnit` and labels the unit `pt` for the normal value 1, or `pdf-user-unit` otherwise.

The rectangle must fit the visible CropBox/MediaBox intersection. The server permits and clamps at most 0.001 units of page-edge rounding error. It rejects larger overflows. Keep full precision when composing API requests rather than rounding intermediate calculations.

Send the object as a JSON-encoded multipart field named `region`. Region placement targets only `region.page`, retaining other pages. It is opt-in: omitting `region` preserves all original raw-coordinate defaults and scopes. Conflicting raw placement/page fields return HTTP 400 rather than silently winning over the selected region.

- `/api/logo/add`: omit `x`, `y`, `width`, `height`, `position`, `scale`, `margin`, `page`, `pages`. Rotation/angle and opacity remain available. The uploaded or default image retains its aspect ratio and is centered inside the selected region; its rotated footprint is fitted inside the rectangle.
- `/api/logo/remove`, `/remove-logo`: omit raw X/Y/width/height and page/pages. The cover fills exactly the region. The main API retains color/debug controls; the legacy route uses its original white cover.
- `/api/watermark/add-watermark`: omit `position`, `margin`, `pages`, `page`, `placementMode`. Text, font size, color, opacity and rotation remain available. Text is centered inside the rectangle; the requested font size shrinks when necessary, without growing beyond the requested size.
- `/add-text`: omit X/Y/width/height/page/pages. `text`, `size` and the original color names remain available. A single line begins inside the region's bottom-left, compensating the source page's rotation; font metrics and fit-down keep its glyphs inside the rectangle.
- `/api/pdf/replace-text`: omit raw X/Y/width/height/page/pages. `newText` and `fontSize` remain available. A white region cover and fitted single-line text replace the visible area. This is still cosmetic replacement, not secure redaction.
- `/api/tools/sign`: omit raw X/Y/width/height/page/pages. A signature image is proportionally fitted and centered; typed signature text is fitted and centered. Existing visual-signature limitations remain.
- `/api/tools/crop`: omit raw X/Y/width/height/page/pages/unit. The selected visible rectangle becomes that page's CropBox. Cropping changes visibility, not the underlying stored content.
- `/a4-to-thermal`: omit `cropPreset`, all four `crop*` coordinates, `allPages`, `pages` and `page`. Rotation and output orientation remain independent. Only the selected source region/page is clipped and fitted into the single thermal output page.
- `/api/tools/redact`: omit `text`, `rectangles`, raw X/Y/width/height/page/pages. The selected region is permanently redacted. Crop-relative coordinates and page rotation are compensated; nondefault UserUnit is normalized internally during redaction and restored so subsequent raw-coordinate measurements remain reusable.
- `/add-logo`: the legacy upload names remain `pdf` and `logo`; omit raw X/Y/width/height/page/pages/position/scale/margin. The image fits the selected region while retaining its proportions.

Selected-region text must be a nonempty single line, use characters supported by the tool's built-in font and fit at a readable size. A region too small to render the text at 0.5 units or more returns HTTP 400. Use a signature image for writing systems unsupported by the built-in typed-signature font.

```bash
curl "$BASE_URL/api/logo/add" -H "X-API-Key: $API_KEY" \
  -F "pdfFile=@document.pdf" -F "logoImage=@logo.png" \
  -F 'region={"page":1,"x":36,"y":72,"width":144,"height":54,"coordinateSpace":"visible"}' \
  -F 'rotation=15' --output branded.pdf
```

## Measurement API: `POST /api/pdf/coordinates`

Upload `pdfFile`. This authenticated, read-only metadata request does not consume a monthly processing operation. Three request shapes are supported:

1. `page=1` (default): return the page's visible dimensions, original rotation, source box and user-unit scale.
2. `page` plus `points`, a JSON array containing exactly two numeric `{x,y}` objects: normalize either corner order into a region and return its native source rectangle.
3. `region`: validate an existing region and return its native source rectangle. Do not combine this form with `page` or `points`.

Points use the same visible bottom-left coordinates, not browser pixels. Both points must lie inside the page; they must define positive width and height. Invalid/password-protected PDFs must be unlocked before this API can measure them.

```bash
curl "$BASE_URL/api/pdf/coordinates" -H "X-API-Key: $API_KEY" \
  -F 'pdfFile=@document.pdf' -F 'page=1' \
  -F 'points=[{"x":36,"y":72},{"x":180,"y":126}]'
```

The JSON response contains `success`, `page`, `coordinateSpace`, `unit`, `userUnit`, `width`, `height`, `rotation` and `sourceBox` (`x/y/width/height` in unrotated absolute PDF coordinates). If a region or two points are supplied, it additionally returns `region` and `sourceRect`. Two-point requests also echo `points`. `sourceRect` is useful for integrations that require native PDF coordinates; for these region-aware tools, send the returned `region` directly.

Preview rulers, grid lines and selection handles are browser overlays and are not added to the saved PDF. The existing `/super-grid` API remains available when a printed coordinate grid is deliberately wanted. Measurement uses the current document revision; after changing page size, crop, orientation or page ordering, measure again rather than reusing stale page geometry.
