> For the complete documentation index, see [llms.txt](https://docs.viesus.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.viesus.com/reference/cloud-api/pdf-enhancement.md).

# Enhance PDFs

PDF enhancement works differently from image enhancement. Before any enhancement can be triggered, the PDF must go through an **analysis phase** that identifies all embedded images and calculates the credit cost. Analysis starts automatically after upload.

***

{% stepper %}
{% step %}

## Upload the PDF

Upload using either method from [Uploading](/reference/cloud-api/uploading.md). Save the returned `id`.

```graphql
mutation {
  createUploadFromUrl(
    input: { url: "https://example.com/photobook.pdf" }
  ) {
    id
    status
  }
}
```

Analysis begins automatically after the upload completes.
{% endstep %}

{% step %}

## Wait for analysis

Query the upload to check analysis progress:

```graphql
query {
  upload(id: "your-upload-id") {
    id
    subStatus
    metadata
  }
}
```

**Analysis status values**

| `subStatus`                      | Meaning               | Action                           |
| -------------------------------- | --------------------- | -------------------------------- |
| `METADATA_ANALYZING`             | Analysis in progress  | Wait or use a webhook            |
| `METADATA_ANALYZED_SUCCESSFULLY` | Ready for enhancement | Proceed to the next step         |
| `METADATA_ANALYZED_FAILED`       | Analysis failed       | Retry with `analyzePdf` mutation |

**Analysis results**

When analysis succeeds, the `metadata` field contains:

* Total image count in the PDF
* Number of images eligible for color enhancement
* Number of images eligible for resizing/upscaling
* Estimated credit cost for different enhancement combinations

Review the credit estimate before triggering enhancement — especially for large PDFs.

**Re-trigger analysis (on failure)**

```graphql
mutation {
  analyzePdf(uploadId: "your-upload-id") {
    success
  }
}
```

Expected response when the re-analysis request is successfully queued:

```json
{ "success": true }
```

If analysis fails repeatedly after multiple re-analysis attempts, this may indicate file format incompatibility, corrupted document content, or system processing limitations. Contact [VIESUS technical support](https://www.viesus.cloud) with your upload ID and file details for further investigation.
{% endstep %}

{% step %}

## Enhance the PDF

Once `subStatus` is `METADATA_ANALYZED_SUCCESSFULLY`:

```graphql
mutation {
  createEnhancedImage(
    uploadId: "your-upload-id"
    input: {
      targetResolution: 300
      upscalingThreshold: 1.2
    }
  ) {
    id
    status
    fullUrl
    filename
    viesusDuration
  }
}
```

**Parameters for PDF enhancement**

| Parameter            | Type                     | Description                                                                                                                            |
| -------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| `targetResolution`   | `Decimal`                | Target output DPI for embedded images                                                                                                  |
| `upscalingThreshold` | `Decimal`                | Minimum scale factor required before upscaling is applied to an image; `1.2` = only upscale images that need more than 20% enlargement |
| `customColorConfig`  | `CustomColorConfigInput` | Manual color adjustments                                                                                                               |

{% hint style="info" %}
PDF enhancement supports only these three parameters. The full image enhancement parameter set (noise reduction, face details, etc.) does not apply to PDFs.
{% endhint %}
{% endstep %}

{% step %}

## Retrieve the enhanced PDF

Check status using the `id` from the previous step:

```graphql
query {
  enhancedImage(id: "enhancement-id") {
    id
    status
    fullUrl
    filename
    viesusDuration
    errorCode
  }
}
```

When `status` is `FINISHED`, the enhanced PDF is available at `fullUrl`.
{% endstep %}
{% endstepper %}

***

## Upscaling limits by subscription

PDF enhancement output resolution is capped by subscription tier:

| Subscription | Maximum output resolution |
| ------------ | ------------------------- |
| Free         | 300 DPI                   |
| Basic        | 600 DPI                   |
| Business     | 1,200 DPI                 |

***

## Webhook events for PDFs

Rather than polling, use webhooks to receive push notifications for both events:

**Analysis complete** — `upload.sub_status_update`:

```json
{
  "id": "eventId",
  "event": "upload.sub_status_update",
  "data": {
    "id": "uploadId",
    "status": "UPLOAD_FINISHED",
    "subStatus": "METADATA_ANALYZED_SUCCESSFULLY",
    "metadata": {
      "statistics": {},
      "totalCredits": 78
    }
  },
  "created": "2025-05-15T14:12:37.501Z"
}
```

**Enhancement complete** — same event structure with `status: FINISHED` on the `enhancedImage`.

See [Webhooks](/reference/cloud-api/webhooks.md) for setup and signature verification.

***

## End-to-end Node.js example

```js
import { GraphQLClient, gql } from 'graphql-request';

const client = new GraphQLClient('https://api.viesus.cloud/graphql', {
  headers: { 'x-api-key': process.env.VIESUS_API_KEY },
});

async function enhancePdf(pdfUrl) {
  // Upload
  const { createUploadFromUrl } = await client.request(gql`
    mutation { createUploadFromUrl(input: { url: "${pdfUrl}" }) { id } }
  `);
  const uploadId = createUploadFromUrl.id;

  // Wait for analysis
  let upload;
  do {
    await new Promise(r => setTimeout(r, 5000));
    upload = (await client.request(gql`
      query { upload(id: "${uploadId}") { subStatus metadata } }
    `)).upload;
  } while (upload.subStatus === 'METADATA_ANALYZING');

  if (upload.subStatus !== 'METADATA_ANALYZED_SUCCESSFULLY') {
    throw new Error(`Analysis failed: ${upload.subStatus}`);
  }

  console.log('Estimated credits:', JSON.parse(upload.metadata).totalCredits);

  // Enhance
  const { createEnhancedImage } = await client.request(gql`
    mutation {
      createEnhancedImage(
        uploadId: "${uploadId}",
        input: { targetResolution: 300, upscalingThreshold: 1.2 }
      ) { id }
    }
  `);

  // Wait for completion
  let result;
  do {
    await new Promise(r => setTimeout(r, 10000));
    result = (await client.request(gql`
      query { enhancedImage(id: "${createEnhancedImage.id}") { status fullUrl errorCode } }
    `)).enhancedImage;
  } while (result.status === 'QUEUED');

  if (result.status === 'ERROR') throw new Error(`Enhancement error: ${result.errorCode}`);
  return result.fullUrl;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.viesus.com/reference/cloud-api/pdf-enhancement.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
