# Document Merge (https://developers.doctavian.com/openapi/latest/reference/Documents/operations-documents-document-merge)

## `POST /documents/document/merge`

**Document Merge**

Merges several PDF files into one PDF and delivers it. List the files in `sourceDocuments`, each with its `urn`, the `loadMethod` that locates it (`Storage`, `OneDrive` or `GoogleDrive`) and its `order`. Every source must be a PDF. Describe the merged file in `targetDocument`: its `name`, `fileFormat` (always `pdf`), `deliveryMethod` and `path`.

**`order` must run 1, 2, 3 … with no gaps.** The sources are merged in ascending `order`, starting at `1` and stopping at the first missing number: a gap leaves out every source after it, a source without `order` counts as `0` and is left out, and if no source has `order` `1` the result is empty. None of these is reported as an error. Two sources with the same `order` fail the request with `500` `MERGE_FUNCTION_FAILED`. A source whose `loadMethod` is not one of the three is skipped without an error.

A `Storage` source is deleted after it is loaded when its `remove` is set to anything other than `none`; leave `remove` out or send `none` to keep it. `OneDrive` and `GoogleDrive` sources are never deleted. Sources are loaded before the merge runs, so a `Storage` source set for removal can already be gone when a later source fails the request.

The response is sent with HTTP `200`, while `result.statusCode` in the body reports `201`. To run the same merge without holding the connection open, use `documents-document-merge-async`.

### Request body (`application/json`)

- `externalContext` (any) — Arbitrary JSON object supplied by the caller and echoed back unchanged in the response, on success and on error alike. Its shape is not validated, fixed or interpreted.
- `sourceDocuments` (array<DocumentMergeSource>) **required** — The PDFs to merge, each with its `order`. Mandatory.
  - `urn` (string) **required** — Mandatory. Identifier of the source PDF in the location given by `loadMethod`: the id the upload returned for `Storage`, or the drive's own file id for `OneDrive` and `GoogleDrive`.
  - `loadMethod` (string) **required** _(enum: "Storage", "OneDrive", "GoogleDrive")_ — Mandatory. Where the source PDF is loaded from: `Storage`, `OneDrive` or `GoogleDrive`, matched exactly, including case. A source with any other value is skipped without an error.
  - `order` (integer) **required** — Mandatory. Position of this source in the merged PDF. The sources are merged in ascending `order`, starting at `1`, and merging stops at the first missing number: a gap leaves out every source after it, and if no source has `order` `1` the result is empty. A source without `order` counts as `0` and is left out. None of these is reported as an error. Two sources with the same `order` fail the request with `500` `MERGE_FUNCTION_FAILED`.
  - `remove` (string) — Whether to delete a `Storage` source after it is loaded. Any value other than `none` deletes it; leave it out or send `none` to keep it. Ignored for `OneDrive` and `GoogleDrive` sources, which are never deleted.
- `targetDocument` (any) **required** — The merged file to produce. Mandatory.
- `data` (object) — Optional data for the resulting file.
  - `embedded` (string) — Optional custom metadata to write into the resulting file's document properties (e.g. PDF metadata), as a JSON-serialized string of key-value pairs. This metadata isn't visible in the document's rendered content but can be read back from the file's properties. Omit it if no custom metadata is needed.

### Responses

#### `200` — The PDFs were merged and the result delivered. `result.statusCode` in the body is `201`. `result.data.document` identifies the merged file, with `uri` and the sharing links for a drive delivery, and `consumption` reports one `documents-merged` entry whose `value` is the number of source files merged.

`application/json`:

_any_

#### `400` — Returned only when the authorization headers that the gateway adds to the request cannot be read. The request is rejected before any work starts, and the body is a bare object, `{ "message": "<reason>" }`, instead of the error envelope. A request that passes the gateway's own token check does not normally reach this case. Invalid input is not reported here: it comes back as `500` — see that response.

#### `403` — A usage limit has been reached, so nothing was done (`LIMIT_BREACH`). The limit is checked before any work starts, against the dimension this request would be counted under. `message` and `userMessage` both name what the limit applies to, the current usage, the limit and the period, in the form "Limit has been breached for {what}. Current usage is {usage}, limit is {limit} for period {period}.", and the root `error.message` is `Forbidden`. `LIMIT_BREACH` is the only entry in `innerErrors`: unlike a `400`, it is not followed by a `MERGE_FUNCTION_FAILED` entry.

`application/json`:

- `error` (object) **required** — What went wrong. `statusCode` and `message` describe the failure category, `innerErrors` the specific causes.
  - `innerErrors` (array<object>) **required** — One entry per distinct problem found with the request. At least one entry is always present, and a request failing several checks reports each of them separately -- read the whole array rather than only the first entry.
    - `code` (string) **required** — Stable, machine-readable Doctavian error code identifying what went wrong, in SCREAMING_SNAKE_CASE. This is the field to branch on in code: the two message fields are prose and may be reworded, but a code, once published, keeps its meaning.
    - `message` (string) **required** — Technical explanation of this specific failure, written for developers and logs. May reference internal specifics and is not safe to show an end user -- use `userMessage` for anything user-facing.
    - `userMessage` (string) **required** — The same failure phrased for an end user and safe to display in a UI verbatim. Says what the user can do about the problem where there is something to do, and never exposes internal detail.
    - `urn` (string) — The request property this error concerns, when the error is about one property. Optional: most errors leave it out. Named by the property's server-side name in PascalCase, not the JSON field name — `TemplateName` for `template.templateName`. Not related to the `urn` that identifies a file elsewhere in the API.
    - `eventId` (string) _(format: uuid)_ — Identifier of the logged failure behind this entry. Present only when the failure was logged, so treat it as optional. Quote it together with `operationId` when reporting the problem to support.
  - `message` (string) **required** — Short summary of the failure category, mirroring the HTTP status text (e.g. `Bad Request`). It names the class of failure only; the specific cause is in `innerErrors`.
  - `statusCode` (integer) **required** — HTTP status code of the error, repeated inside the body so the envelope stays self-contained when it is logged or forwarded. Always a number, never a string, and always equal to the response's own HTTP status.
  - `externalErrors` (array<any>) — Additional error detail attached as the server produced it. Each entry can be any JSON value and its shape is not fixed: an object returned by an external service the request depended on — such as the Google Apps Script execution layer used for `gdoc`, `gsheet` and `gslide` generation — or a plain string, such as the message of an unhandled exception. Use it for diagnostics only, and branch on `innerErrors[].code` instead. Empty or absent when there is nothing to add.
- `dateTime` (string) **required** _(format: date-time)_ — UTC timestamp when the error response was generated, with between three and seven decimal places. Doctavian's own responses end in `Z`; a response from the gateway — a `401` for a missing or invalid credential, or a `404` for a request that matches no operation — has seven decimal places and ends in `+00:00` instead.
- `operationId` (string) — Identifier of this operation in Doctavian's Azure logs, generated per request and returned on both success and failure. This is the primary reference to quote when reporting a problem to support; when `eventId` is also present, quote both. Left out of a response from the gateway, which answers some requests before they reach Doctavian: a `401` for a missing or invalid credential, and a `404` for a request that matches no operation, such as one without a mandatory query parameter. Such a response has no operation to log, and its `origin` may be empty.
- `eventId` (string) _(format: uuid)_ — Identifier of the corresponding entry in Doctavian's server-side error log. Present only when the failure was handled and logged, so treat it as optional and don't rely on it being there. When reporting a problem to support, quote it together with `operationId`: `operationId` identifies the request that was made, `eventId` identifies the logged failure behind it, and having both is what lets support trace the request end to end. A failure can instead, or also, carry an `eventId` on individual `innerErrors` entries.
- `origin` (string) **required** — The HTTP method and full request URL that produced this response, e.g. `POST https://api.doctavian.com/v1/documents/document/generate`. Useful when the envelope is logged or forwarded away from the call that produced it.
- `userId` (string) _(format: uuid)_ — The unique identifier of the user or system that initiated the request. Left out of the response when the request carried no bearer token — a guest caller on an operation that does not require one, such as a recipient signing with a `tid` — because there is no signed-in user to identify. Also left out when the caller has no Doctavian user yet: `platform-subscription-resolve` and `platform-subscription-trial-start` run before the caller's user exists, so their responses carry no `userId`.
- `externalContext` (object) — Optional, arbitrary JSON object echoed back unchanged from the request's externalContext, if one was supplied. Used to correlate this response with the request that produced it.

#### `500` — The merge failed because of a server-side error (`MERGE_FUNCTION_FAILED`). Also returned when two sources have the same `order`. When the cause is known, a specific entry comes first: `FILE_LOAD_STORAGE_FAILED`, or `FILE_MISSING_FROM_STORAGE` followed by `GET_FILE_FROM_STORAGE_FAILED`, when a `Storage` source named by a `sourceDocuments[].urn` cannot be found or loaded. A `Storage` source is deleted once it has been loaded, so this is also what a second call with the same `urn` returns. The entry carries an `eventId` when the failure was logged — quote it together with `operationId` when reporting the problem to support. Invalid input is reported here too, not as `400`: an invalid `targetDocument.deliveryMethod` returns `INVALID_DELIVERY_METHOD_SPECIFIED` followed by `MERGE_FUNCTION_FAILED`.

`application/json`:

- `error` (object) **required** — What went wrong. `statusCode` and `message` describe the failure category, `innerErrors` the specific causes.
  - `innerErrors` (array<object>) **required** — One entry per distinct problem found with the request. At least one entry is always present, and a request failing several checks reports each of them separately -- read the whole array rather than only the first entry.
    - `code` (string) **required** — Stable, machine-readable Doctavian error code identifying what went wrong, in SCREAMING_SNAKE_CASE. This is the field to branch on in code: the two message fields are prose and may be reworded, but a code, once published, keeps its meaning.
    - `message` (string) **required** — Technical explanation of this specific failure, written for developers and logs. May reference internal specifics and is not safe to show an end user -- use `userMessage` for anything user-facing.
    - `userMessage` (string) **required** — The same failure phrased for an end user and safe to display in a UI verbatim. Says what the user can do about the problem where there is something to do, and never exposes internal detail.
    - `urn` (string) — The request property this error concerns, when the error is about one property. Optional: most errors leave it out. Named by the property's server-side name in PascalCase, not the JSON field name — `TemplateName` for `template.templateName`. Not related to the `urn` that identifies a file elsewhere in the API.
    - `eventId` (string) _(format: uuid)_ — Identifier of the logged failure behind this entry. Present only when the failure was logged, so treat it as optional. Quote it together with `operationId` when reporting the problem to support.
  - `message` (string) **required** — Short summary of the failure category, mirroring the HTTP status text (e.g. `Bad Request`). It names the class of failure only; the specific cause is in `innerErrors`.
  - `statusCode` (integer) **required** — HTTP status code of the error, repeated inside the body so the envelope stays self-contained when it is logged or forwarded. Always a number, never a string, and always equal to the response's own HTTP status.
  - `externalErrors` (array<any>) — Additional error detail attached as the server produced it. Each entry can be any JSON value and its shape is not fixed: an object returned by an external service the request depended on — such as the Google Apps Script execution layer used for `gdoc`, `gsheet` and `gslide` generation — or a plain string, such as the message of an unhandled exception. Use it for diagnostics only, and branch on `innerErrors[].code` instead. Empty or absent when there is nothing to add.
- `dateTime` (string) **required** _(format: date-time)_ — UTC timestamp when the error response was generated, with between three and seven decimal places. Doctavian's own responses end in `Z`; a response from the gateway — a `401` for a missing or invalid credential, or a `404` for a request that matches no operation — has seven decimal places and ends in `+00:00` instead.
- `operationId` (string) — Identifier of this operation in Doctavian's Azure logs, generated per request and returned on both success and failure. This is the primary reference to quote when reporting a problem to support; when `eventId` is also present, quote both. Left out of a response from the gateway, which answers some requests before they reach Doctavian: a `401` for a missing or invalid credential, and a `404` for a request that matches no operation, such as one without a mandatory query parameter. Such a response has no operation to log, and its `origin` may be empty.
- `eventId` (string) _(format: uuid)_ — Identifier of the corresponding entry in Doctavian's server-side error log. Present only when the failure was handled and logged, so treat it as optional and don't rely on it being there. When reporting a problem to support, quote it together with `operationId`: `operationId` identifies the request that was made, `eventId` identifies the logged failure behind it, and having both is what lets support trace the request end to end. A failure can instead, or also, carry an `eventId` on individual `innerErrors` entries.
- `origin` (string) **required** — The HTTP method and full request URL that produced this response, e.g. `POST https://api.doctavian.com/v1/documents/document/generate`. Useful when the envelope is logged or forwarded away from the call that produced it.
- `userId` (string) _(format: uuid)_ — The unique identifier of the user or system that initiated the request. Left out of the response when the request carried no bearer token — a guest caller on an operation that does not require one, such as a recipient signing with a `tid` — because there is no signed-in user to identify. Also left out when the caller has no Doctavian user yet: `platform-subscription-resolve` and `platform-subscription-trial-start` run before the caller's user exists, so their responses carry no `userId`.
- `externalContext` (object) — Optional, arbitrary JSON object echoed back unchanged from the request's externalContext, if one was supplied. Used to correlate this response with the request that produced it.