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

# PDF Export API

> Nextedy RISKSHEET generates PDF documents from grid data using a customizable export pipeline.

export const LastReviewed = ({date}) => {
  if (!date) return null;
  const formatted = new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    timeZone: "UTC"
  });
  return <p className="mt-10 text-sm text-gray-400 dark:text-zinc-500 not-prose">
      Last reviewed on {formatted}
    </p>;
};

<Frame>
  <img src="https://mintcdn.com/none-17b4493f/yWl5nA2D0IzEnZC1/risksheet/diagrams/reference/api/pdf-export-api/diagram-1.svg?fit=max&auto=format&n=yWl5nA2D0IzEnZC1&q=85&s=db2bed6481f0d9ea3d086ea177ad144a" alt="diagram" style={{ maxWidth: "520px", width: "100%" }} width="520" height="440" data-path="risksheet/diagrams/reference/api/pdf-export-api/diagram-1.svg" />
</Frame>

## Prerequisites

PDF export requires the sheet to be in a clean state. The export command validates two conditions before proceeding:

| Condition       | Check                      | Behavior if Failed                             |
| --------------- | -------------------------- | ---------------------------------------------- |
| Unsaved changes | `isDirty()` returns `true` | Export blocked; user prompted to save          |
| Comparison mode | `ComparisonManager` exists | Export blocked; user must exit comparison view |

<Warning title="Save Before Export">
  Always save your changes before exporting to PDF. The export reads the last saved revision of the document to ensure the PDF reflects a consistent, committed state.
</Warning>

## Server Endpoint

| Property           | Value                                     |
| ------------------ | ----------------------------------------- |
| Endpoint           | `/api/pdfscript`                          |
| Method             | GET                                       |
| Required parameter | `revision` (document revision identifier) |
| Response           | Generated JavaScript export script        |
| Template file      | `risksheetPdfExport.vm`                   |

The server loads the `risksheetPdfExport.vm` Velocity template, renders it with the full Velocity context (including document, transaction, and `pdfExportMacros.vm` helper macros), and returns the generated JavaScript code to the browser for execution.

## PDF Export Configuration Properties

### Template Properties

| Property                 | Type      | Default                 | Description                                                                                                                            |
| ------------------------ | --------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `risksheetPdfExport.vm`  | `string`  | `risksheetPdfExport.vm` | Name of the Velocity template file attached to the document or inherited from a template. Contains the export script configuration.    |
| `pdfExportConfiguration` | `string`  | None                    | Full content of the PDF export Velocity template as a string. Loaded from the template file.                                           |
| `templateName`           | `string`  | None                    | Name of the template from which the PDF export configuration was loaded. Empty when the template is attached directly to the document. |
| `fromTemplate`           | `boolean` | `false`                 | Flag indicating whether the PDF export configuration was loaded from a template rather than a document attachment.                     |
| `configPath`             | `string`  | None                    | Repository path to the sheet configuration that was loaded. Useful for debugging template resolution.                                  |
| `fileName`               | `string`  | None                    | Name of the sheet configuration. Tracks which file contains the PDF export configuration.                                              |

### Export Command Properties

| Property           | Type      | Default         | Description                                                                                                                                                                     |
| ------------------ | --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mergeCacheFlag`   | `boolean` | See application | Controls how merged cells are rendered in the PDF export. Logged during export initialization.                                                                                  |
| `masterMergeOnly`  | `boolean` | See application | Determines whether the PDF export uses a flat table structure or hierarchical row merging. When `true`, only master-level merges are applied.                                   |
| `emptyPlaceholder` | `string`  | `null`          | Text to display in the PDF for null or empty cells. When `null`, empty cells are left blank. Set this in your custom export script to show a placeholder like `"-"` or `"N/A"`. |

## Export Functions

The export script has access to the following functions through the `exporter` object. Each function renders a specific type of table in the PDF output.

### exportMainSheet

Exports the primary Risksheet grid to PDF.

| Parameter     | Type     | Description                                                                                                                                       |
| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hideColumns` | `string` | Comma-separated list of column binding names to exclude from the PDF output. Columns are temporarily hidden during export and restored afterward. |

```javascript theme={null}
// Export main grid, hiding the internal ID and revision columns
exporter.exportMainSheet("systemItemId,systemItemRevision");

// Export all visible columns
exporter.exportMainSheet("");
```

<Tip title="Column Visibility">
  Use `hideColumns` to exclude internal or administrative columns that are useful in the interactive grid but not needed in printed output. The columns are hidden temporarily during PDF rendering and restored immediately after.
</Tip>

### exportSubTable

Exports a filtered sub-table containing only rows where a specified control column has non-empty values.

| Parameter       | Type     | Description                                                                                              |
| --------------- | -------- | -------------------------------------------------------------------------------------------------------- |
| `controlColumn` | `string` | Column binding name used to filter rows. Only rows where this column has a non-empty value are included. |

```javascript theme={null}
// Export a sub-table of mitigation tasks
exporter.exportSubTable("mitigationTask");
```

Typical use cases include exporting separate tables for mitigation tasks, verification activities, or other task-level data that you want to present independently from the main risk table.

### exportDownstreamTable

Exports downstream traceability tables with deduplication. Unlike `exportSubTable`, this function tracks which control column values have already been processed and skips duplicate rows, producing a table of unique downstream relationships.

| Parameter       | Type     | Description                                                                                                                     |
| --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `controlColumn` | `string` | Column binding name for the downstream link. Rows with duplicate values in this column are excluded after the first occurrence. |

```javascript theme={null}
// Export unique downstream mitigation actions
exporter.exportDownstreamTable("actionItem");
```

### exportRatingTable

Exports a risk rating definition table with three columns: ID, Label, and Description. Rating data is read from the Polarion enumeration referenced by the `rating:<enumId>` column, not from any section of the sheet configuration.

| Parameter  | Type     | Description                                                                                                                                                      |
| ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ratingId` | `string` | The enumeration ID identifying which rating scale to export. Matches the `<enumId>` of a `rating:<enumId>` column type, which references a Polarion enumeration. |

```javascript theme={null}
// Export severity rating definitions
exporter.exportRatingTable("severity");

// Export occurrence rating definitions
exporter.exportRatingTable("occurrence");

// Export detection rating definitions
exporter.exportRatingTable("detection");
```

The output table always has three columns:

| Column      | Source        |
| ----------- | ------------- |
| ID          | `rating.id`   |
| Label       | `rating.name` |
| Description | `rating.desc` |

### exportEnumTable

Exports an enumeration value table showing ID, Label, and Description for a Polarion enumeration referenced by an `enum:<enumId>` or `multiEnum:<enumId>` column.

| Parameter | Type     | Description                                                                                                                                                                            |
| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enumId`  | `string` | The enumeration ID identifying which enumeration to export. Matches the `<enumId>` of an `enum:<enumId>` or `multiEnum:<enumId>` column type, which references a Polarion enumeration. |

```javascript theme={null}
// Export failure mode categories
exporter.exportEnumTable("failureCategory");
```

### exportCustomTableData

Exports arbitrary tabular data with custom column definitions and optional absolute positioning.

| Parameter | Type     | Description                                                                                |
| --------- | -------- | ------------------------------------------------------------------------------------------ |
| `columns` | `array`  | Array of column definition objects, each with `binding`, `header`, and `width` properties. |
| `data`    | `array`  | Array of data row objects with keys matching the column bindings.                          |
| `xpos`    | `number` | (Optional) Horizontal position in points for absolute placement on the PDF page.           |
| `ypos`    | `number` | (Optional) Vertical position in points for absolute placement on the PDF page.             |

```javascript theme={null}
// Export a custom summary table
exporter.exportCustomTableData(
  [
    { binding: "category", header: "Risk Category", width: 200 },
    { binding: "count", header: "Count", width: 80 },
    { binding: "maxRpn", header: "Max RPN", width: 80 }
  ],
  [
    { category: "Electrical", count: 12, maxRpn: 480 },
    { category: "Mechanical", count: 8, maxRpn: 320 },
    { category: "Software", count: 15, maxRpn: 560 }
  ]
);
```

## Script Context Variables

The generated export script has access to the following scope variables:

| Variable          | Type      | Description                                                          |
| ----------------- | --------- | -------------------------------------------------------------------- |
| `exporter`        | `object`  | Export helper object providing all `export*` functions listed above. |
| `PDFExport`       | `object`  | Low-level PDF generation API for advanced customization.             |
| `GridPDF`         | `object`  | Grid-to-PDF rendering engine.                                        |
| `isInCompare`     | `boolean` | Whether the export is running in comparison mode.                    |
| `compareRevision` | `string`  | Revision being compared against (if in comparison mode).             |
| `currentRevision` | `string`  | Current document revision being exported.                            |
| `showUnchanged`   | `boolean` | Whether to include unchanged rows in comparison exports.             |

<Info title="Application State">
  The export command passes the current application state (`app.state`) to the PDF renderer. This means the exported PDF reflects the current view configuration, including top panel settings and active filters.
</Info>

## Cell Formatting in PDF

The export engine automatically handles cell formatting for different column types:

| Column Type          | PDF Rendering                                                     |
| -------------------- | ----------------------------------------------------------------- |
| Text / String        | Plain text value                                                  |
| Boolean / Checkbox   | `true` or `false` text                                            |
| Enum                 | Resolved display name from enum configuration                     |
| Multi-Enum           | Comma-separated list of resolved display names                    |
| Item Link            | Label text from the linked work item                              |
| Multi-Item Link      | Newline-separated list of linked item labels                      |
| Server-Rendered HTML | Stripped to plain text with line breaks preserved from list items |
| System Item ID       | Standard item identifier                                          |
| Calculated / Formula | Computed value at time of export                                  |
| Empty / Null         | Value of `emptyPlaceholder` if set, otherwise blank               |

<Warning title="Known Limitations">
  Based on reported issues, be aware of the following PDF export behaviors:

  * **Enum fields**: Regular enums export with display titles, but rating fields (numeric IDs) and user reference fields may export with internal IDs instead of display names. Use saved views as an alternative export mechanism for consistent formatting.
  * **Risk matrix calculations**: Risk matrix totals in PDF export may not correctly count risks across all severity categories in some configurations. Verify risk matrix counts against the interactive grid.
  * **Long text overflow**: Tables may not automatically expand to accommodate long text content. Test your PDF export with representative data to verify layout.
  * **Baselines**: PDF export baseline display may show incorrect or missing baselines in variant projects. Baselines should be identified by document ID/path for reliability.
</Warning>

## Template Inheritance for PDF Export

The `risksheetPdfExport.vm` template follows the same inheritance chain as the main sheet configuration:

1. **Document attachment** (highest priority) --- Template file attached directly to the LiveDoc document
2. **Template document** --- Inherited from the document's Polarion template
3. **Global template** --- Project-level default template configuration

To create a document-specific PDF export template, use **Menu > Override Template** to detach from the inherited configuration, then attach a custom `risksheetPdfExport.vm` file to the document.

## Complete Example

A typical `risksheetPdfExport.vm` export script that produces a complete FMEA report:

```javascript theme={null}
// Export the main FMEA risk table, hiding internal columns
exporter.exportMainSheet("systemItemId,systemItemRevision");

// Export severity rating definitions
exporter.exportRatingTable("severity");

// Export occurrence rating definitions
exporter.exportRatingTable("occurrence");

// Export detection rating definitions
exporter.exportRatingTable("detection");

// Export downstream mitigation actions as a separate table
exporter.exportDownstreamTable("mitigationTask");
```

## Progress Feedback

During PDF generation, Risksheet displays a persistent toast notification:

| Property           | Value                                              |
| ------------------ | -------------------------------------------------- |
| Title              | `Exporting to PDF`                                 |
| Message            | `Please wait while the file is being generated...` |
| Display time       | Persistent (dismissed on completion)               |
| Progress indicator | Animated progress image                            |

The notification remains visible until the PDF file is generated and the download begins.

## Related Pages

* [PDF Export Template](/risksheet/reference/templates/pdf-export-template) for the Velocity template syntax and macro reference
* [Velocity Template Context](/risksheet/reference/api/velocity-context) for the full list of context variables available in export templates
* [Custom Renderer Templates](/risksheet/reference/templates/custom-renderers) for cell-level rendering customization
* [Configuration Properties Index](/risksheet/reference/configuration/properties-index) for all configurable properties

<LastReviewed date="2026-06-24" />
