# PDF

> Language fallback: requested `zh-CN`; content is `en-US`.

- Human documentation: [https://docs.univer.ai/zh-CN/reference/facade/pdf](https://docs.univer.ai/zh-CN/reference/facade/pdf)

- Agent Markdown: [https://docs.univer.ai/zh-CN/reference/facade/pdf.md](https://docs.univer.ai/zh-CN/reference/facade/pdf.md)

- Requested language: `zh-CN`

- Content language: `en-US`

- Documentation version: `1.0.0-rc.0`

- Source: [facade/pdf.mdx](https://github.com/dream-num/documentation/blob/dev/content/reference/facade/pdf.mdx)

---

| Packages | `@univerjs-pro/pdfs` |
| -------- | -------------------- |

Facade APIs for creating, reading, and editing Univer PDF units.

> Import `@univerjs-pro/pdfs/facade` before using these APIs in plugin mode.

For setup and task-oriented examples, start with the [Univer PDFs guide](https://docs.univer.ai/zh-CN/guides/pdfs.md).

## Before using the API

Register `UniverPdfsPlugin` and import `@univerjs-pro/pdfs/facade` after `@univerjs/core/facade`. Browser editing also needs `UniverPdfsUIPlugin`, its CSS, and the client license configuration. See [installation](https://docs.univer.ai/zh-CN/guides/pdfs/getting-started/installation.md).

PDF positions and sizes use **PDF points**, not CSS pixels. Page indexes and element indexes are zero-based. Use `save()` to persist accepted edits; `getDocument()` returns the source document and does not replace a complete snapshot. See the [PDF data model](https://docs.univer.ai/zh-CN/guides/pdfs/model/pdf-data.md).

## Unit access

```typescript
createPdf(data?: Partial<IPdfUnitData>, options?: ICreateUnitOptions): FPdf
getActivePdf(): FPdf | null
getPdf(id: string): FPdf | null
getPdfTableThemePresets(): ReadonlyArray<Readonly<IPdfTableThemePreset>>
```

`createPdf()` returns a new `FPdf`; omitting `data` creates a blank unit. Supply a complete snapshot to restore saved content. `getActivePdf()` and `getPdf(id)` return `null` if no matching PDF exists, so check the result before editing.

## FPdf

| Category          | Methods                                                   |
| ----------------- | --------------------------------------------------------- |
| Identity and data | `getId`, `getName`, `save`, `getDocument`, `getModel`     |
| Pages             | `insertPage`, `getPages`, `getPageById`, `getPageByIndex` |

```typescript
getId(): string
getName(): string
save(): IPdfUnitData
getDocument(): IPdfDocument
getModel(): PdfDocumentModel
insertPage(index?: number): FPdfPage
getPages(): FPdfPage[]
getPageById(id: string): FPdfPage | null
getPageByIndex(index: number): FPdfPage | null
```

### Page access and persistence

| Method                  | Parameters                                               | Result and behavior                                                                                                                                 |
| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `insertPage(index?)`    | Optional integer from `0` through the current page count | Returns `FPdfPage`; omission appends. Throws `RangeError` for an invalid index. The first page uses A4; later pages inherit adjacent page geometry. |
| `getPageByIndex(index)` | Zero-based page index                                    | Returns `FPdfPage` or `null` when absent.                                                                                                           |
| `getPageById(id)`       | Stable page ID                                           | Returns `FPdfPage` or `null` when absent.                                                                                                           |
| `save()`                | None                                                     | Returns a detached `IPdfUnitData` snapshot with current edits.                                                                                      |
| `getDocument()`         | None                                                     | Returns the source `IPdfDocument` baseline.                                                                                                         |

## FPdfPage

`FPdfPage` resolves existing page elements and inserts editable text boxes, paragraphs, lists, tables, dividers, annotations, and images.

```typescript
getId(): string
getIndex(): number
getData(): Readonly<IPdfPage>
getElements(): FPdfPageElement[]
getElementById(id: string): FPdfPageElement | null
getTextBoxes(): FPdfTextBox[]
getImages(): FPdfImage[]
getParagraphs(): FPdfParagraph[]
getLists(): FPdfList[]
getTables(): FPdfTable[]
getDividers(): FPdfDivider[]
getAnnotations(): FPdfAnnotation[]
getTextSpans(): FPdfTextSpan[]
insertTextBox(options: IPdfTextBoxInsertOptions): FPdfTextBox
insertParagraph(options: IPdfParagraphInsertOptions): FPdfParagraph
insertList(options: IPdfListInsertOptions): FPdfList
insertTable(options: IPdfTableInsertOptions): FPdfTable
insertDivider(options?: IPdfDividerInsertOptions): FPdfDivider
insertAnnotation(options: IPdfAnnotationInsertOptions): FPdfAnnotation
newImage(existing?: FPdfImage | string): FPdfImageBuilder
insertImage(info: IPdfImageBuilderInfo, index?: number): FPdfImage
insertImageAsync(source: string | IFBlobSource, options?: IPdfImageInsertOptions): Promise<FPdfImage>
```

### Insertion parameters

Text boxes, paragraphs, lists, tables, dividers, annotations, and images share `IPdfElementInsertOptions`:

| Property          | Type      | Meaning                                                                                      |
| ----------------- | --------- | -------------------------------------------------------------------------------------------- |
| `id`              | `string?` | Stable element ID; generated if omitted.                                                     |
| `left`, `top`     | `number?` | Position in PDF points; default `0`.                                                         |
| `width`, `height` | `number?` | Size in PDF points; defaults depend on the element type.                                     |
| `rotation`        | `number?` | Clockwise degrees; default `0`.                                                              |
| `index`           | `number?` | Zero-based position in the editable element stack; omission places the element at the front. |

#### Text boxes and paragraphs

`insertTextBox(options)` returns `FPdfTextBox`; `insertParagraph(options)` returns `FPdfParagraph`.

| Property     | Type        | Meaning                                           |
| ------------ | ----------- | ------------------------------------------------- |
| `text`       | `string`    | Required initial text; an empty string is valid.  |
| `fontFamily` | `string?`   | Initial font family; renderer default if omitted. |
| `fontSize`   | `number?`   | Initial size in points; default `12`.             |
| `fill`       | `PdfColor?` | Initial text color.                               |

#### Tables

`insertTable(options)` returns `FPdfTable`.

| Property                  | Type                     | Meaning                                                                 |
| ------------------------- | ------------------------ | ----------------------------------------------------------------------- |
| `rowCount`, `columnCount` | `number`                 | Required positive initial dimensions.                                   |
| `cellTexts`               | `string[]?`              | Initial values in row-major order; missing cells contain empty strings. |
| `defaultCellStyle`        | `IPdfTableCellStyle?`    | Style copied to each initial cell.                                      |
| `styleId`                 | `PdfStyleId?`            | Table style ID; use a table theme preset or the default.                |
| `options`                 | `IPdfTableStyleOptions?` | Conditional table-style regions.                                        |

#### Images

`insertImageAsync(source, options?)` accepts a URL string or `IFBlobSource` and returns `Promise<FPdfImage>`. Await completion before saving the snapshot. Image options add `imageSourceType`, `crop`, and `opacity` (`0` through `1`, default `1`) to the shared placement fields. See [images](https://docs.univer.ai/zh-CN/guides/pdfs/features/core/images-and-dividers.md).

### Errors and lifetime

Mutations throw when the action is rejected. Invalid page insertion indexes throw `RangeError`. Catch errors at the application interaction boundary and present the failed operation to the user. Do not continue using page or element wrappers after their owning unit is disposed. Dispose the owning `univer` instance when unmounting the editor.

## Page elements

Every `FPdfPageElement` supports identity, transform, visibility, locking, z-order, and removal. Specialized wrappers add content editing:

| Wrapper          | Methods                                                                                                       |
| ---------------- | ------------------------------------------------------------------------------------------------------------- |
| `FPdfTextBox`    | `getText`, `getTextRuns`, `setText`, `setTextStyle`, `getTextAnchor`, `setTextAnchor`                         |
| `FPdfParagraph`  | `getBlocks`, `insertBlock`, `appendBlock`, `setBlockText`, `setBlockStyle`, `removeBlock`                     |
| `FPdfList`       | `getItems`, `insertItem`, `setItemText`, `removeItem`, `changeItemLevel`, `setPreset`, `setStartNumber`       |
| `FPdfTable`      | `getRowCount`, `getColumnCount`, `getCell`, `resize`, `getTheme`, `setTheme`                                  |
| `FPdfTableCell`  | `getText`, `setText`, `getStyle`, `setStyle`                                                                  |
| `FPdfDivider`    | `getStroke`, `setStroke`                                                                                      |
| `FPdfAnnotation` | `getAnnotationType`, `getMarkup`, `getInk`, `getStyle`, `setStyle`                                            |
| `FPdfImage`      | `getSource`, `getImageSourceType`, `setSource`, `getCrop`, `setCrop`, `getOpacity`, `setOpacity`, `toBuilder` |
| `FPdfTextSpan`   | `getId`, `getText`, `getTextRuns`, `getBounds`, `replaceText`                                                 |

```typescript
// FPdfPageElement
getId(): string
getType(): PdfObjectType
getData(): Readonly<PdfObject>
getTransform(): IPdfFacadeTransform
setTransform(transform: IPdfFacadeTransform): this
setPosition(left: number, top: number): this
setSize(width: number, height: number): this
setRotation(rotation: number): this
setVisible(visible: boolean): this
setLocked(locked: boolean): this
bringToFront(): this
sendToBack(): this
bringForward(): this
sendBackward(): this
remove(): void
```

```ts
import '@univerjs-pro/pdfs/facade'

const pdf = univerAPI.createPdf({ name: 'Project brief' })
const page = pdf.insertPage()

page.insertTextBox({ text: 'Hello PDF', left: 36, top: 36 }).setTextStyle({ fontSize: 18, fill: '#274690' })

page.insertTable({
  left: 36,
  top: 90,
  rowCount: 2,
  columnCount: 2,
  cellTexts: ['Metric', 'Value', 'Users', '42'],
})

const snapshot = pdf.save()
// Store snapshot in your application; pass it to createPdf(snapshot) when restoring.
```

PDF facade enums include `PdfAnnotationType`, `PdfListKind`, `PdfListPresetId`, `PdfTextAnchor`, and `PdfTableCellVerticalAlign` through `univerAPI.Enum`.

For browser printing, see [`@univerjs-pro/pdfs-print`](https://docs.univer.ai/zh-CN/reference/packages/plugins/univerjs-pro/pdfs-print.md).

Source: 

`@univerjs-pro/pdfs`
