# Attachments and portfolios

> Embed any file in a PDF with its type, description, relationship and checksum, list, open and remove attachments, read PDF portfolios, and handle the attachmentOpen event and drag-and-drop in the viewer.

A PDF can carry other files: the spreadsheet a report was built from, the email a contract arrived in, a ZIP of delivery notes. Birch UI PDF embeds any bytes you hand it. The file is stored as it is and never interpreted, so Outlook messages, Office documents, images, archives and other PDFs all work the same way.

## Adding, listing and removing

```ts
import { readFile } from 'node:fs/promises';

pdf.addAttachment({
  name: 'Übersicht Q3 – 売上.xlsx',
  data: await readFile('exports/q3-revenue.xlsx'),
  description: 'Revenue by region, third quarter',
  relationship: 'Data',
  modified: new Date('2026-09-30T16:00:00Z'),
});

for (const file of pdf.getAttachments()) {
  console.info(file.name, file.mimeType, file.size, file.relationship, file.checksum, file.isChecksumValid);
}

pdf.removeAttachment('Übersicht Q3 – 売上.xlsx');
```

| `AttachmentInput` | Meaning |
| --- | --- |
| `name` | File name shown to the reader. Any Unicode text. |
| `data` | The bytes of the file |
| `mimeType` | Media type. Left out, it is taken from the file extension, and is `application/octet-stream` for an unknown one. |
| `description` | Free text shown next to the name |
| `created`, `modified` | Dates of the file. `modified` defaults to `created`, then to now. |
| `relationship` | How the file relates to the document; see below. Default `Unspecified`. |

`getAttachments()` returns the document-level files (`source: 'document'`) and the files of file attachment annotations (`source: 'annotation'`, with a `pageIndex`). Each entry has `name`, `data`, `size`, and, when the file specification carries them, `mimeType`, `description`, `created`, `modified`, `relationship`, `checksum` and `isChecksumValid`. Files written by other tools often lack some of these; the fields are then absent, never guessed.

Adding a file under a name that already exists replaces it. `removeAttachment(name)` removes a document-level file and returns whether one was found. Both are one undo step each.

The types the extension lookup knows are `pdf`, `msg` (`application/vnd.ms-outlook`), `eml` (`message/rfc822`), `docx`, `xlsx`, `pptx`, `doc`, `xls`, `ppt`, `zip`, `csv`, `json`, `xml`, `txt`, `html`, `png`, `jpg`/`jpeg`, `gif`, `bmp`, `webp`, `svg`, `tif`/`tiff`, `mp3`, `wav` and `mp4`. `mimeTypeForFileName(name)` is exported if you need the same lookup.

## What is written

Every attachment is a file specification as described in ISO 32000-2, 7.11.4:

- `/F` and `/UF` both hold the name. `/UF` is the exact name, as UTF-16 when it is not plain ASCII. `/F` is a compatibility copy in PDFDocEncoding in which characters that encoding lacks are replaced by `_`.
- `/EF` points to the embedded file stream under both `/F` and `/UF`.
- `/Desc` holds the description and `/AFRelationship` the relationship.
- The stream has `/Type /EmbeddedFile`, the media type as `/Subtype` (written as a name, so `application/pdf` is `application#2Fpdf` in the file), and `/Params` with `/Size`, `/CreationDate`, `/ModDate` and `/CheckSum`.
- The stream is compressed with Flate when the document is saved and compression makes it smaller (`save({ compress: false })` turns that off). `/Params /Size` and `/DL` always give the size of the original file.

The embedded files name tree is kept sorted, and when one name needs UTF-16 all keys are written as UTF-16 so that the byte order stays consistent.

### Relationships and PDF/A-3

`relationship` is one of `Source`, `Data`, `Alternative`, `Supplement`, `EncryptedPayload`, `FormData`, `Schema` or `Unspecified`. It answers "what is this file to the document": the source it was made from, the data behind a chart, another representation of the same content, or supplementary material.

A relationship other than `Unspecified` also adds the file to the `/AF` array of the document catalog, which is how PDF 2.0 and PDF/A-3 associate a file with the document as a whole. Removing or replacing the file removes its `/AF` entry.

```ts
import { ATTACHMENT_RELATIONSHIPS, type AttachmentRelationship } from '@birchui/pdf/engine';

declare const invoiceXmlBytes: Uint8Array;

const relationship: AttachmentRelationship = 'Alternative';
if (ATTACHMENT_RELATIONSHIPS.includes(relationship)) {
  pdf.addAttachment({ name: 'factur-x.xml', data: invoiceXmlBytes, mimeType: 'text/xml', relationship });
}
```

Writing `/AFRelationship` and `/AF` is necessary for PDF/A-3 but does not make a file PDF/A-3. Conformance also needs the right XMP metadata, embedded fonts, an output intent and more, and e-invoice profiles such as Factur-X add their own XMP schema. Birch UI PDF does not validate or produce PDF/A; see the [archive readiness check](https://docs.birchui.com/pdf/document-tools.md#archive-readiness-check) for what it can report.

### Checksums

`/CheckSum` is the MD5 digest of the file, as the PDF specification defines it. It guards against accidental damage, not against tampering. On reading, `checksum` is the stored digest in hex and `isChecksumValid` says whether it matches the bytes that were read. Both are absent when the file has no checksum.

```ts
const damaged = pdf.getAttachments().filter((file) => file.isChecksumValid === false);
if (damaged.length > 0) console.warn('Changed since they were embedded:', damaged.map((file) => file.name));
```

### File names

Names are free text: spaces, parentheses, backslashes, accented letters and CJK characters round-trip unchanged through `/UF`. A reader that only looks at `/F` sees the compatibility copy, for example `Übersicht Q3 – __.xlsx` for the name in the first sample. When you save an attachment to disk yourself, replace the characters your file system does not allow.

## File attachment annotations

A file can also be pinned to a place on a page. The annotation uses the same file specification as a document-level attachment, including the relationship and the checksum.

```ts
declare const inspectionBytes: Uint8Array;

const pin = pdf.addAnnotation({
  type: 'fileAttachment',
  pageIndex: 0,
  rect: [500, 700, 520, 724],
  iconName: 'Paperclip',
  attachment: { fileName: 'Prüfprotokoll – Halle 3.txt', data: inspectionBytes, relationship: 'Supplement' },
});
const file = pdf.getAnnotationAttachment(pin.id);
console.info(file?.fileName, file?.mimeType, file?.data.length);
```

Files of annotations are not added to the catalog `/AF` array, because they belong to the annotation and not to the document as a whole. See [Attachments and media](https://docs.birchui.com/pdf/annotations.md#attachments-and-media) for the annotation itself.

## Portfolios

A portfolio (a "collection" in the specification, ISO 32000-1, 12.3.5) is a PDF whose attachments are the content, shown by a reader as a table with columns the author defined. `getCollection()` returns that description, or `undefined` for an ordinary document.

```ts
const collection = pdf.getCollection();
if (collection) {
  console.info(collection.view, collection.initialDocument, collection.sort);
  const columns = collection.fields.filter((field) => field.isVisible);
  for (const item of collection.items) {
    console.info(columns.map((field) => `${field.name}: ${String(item.values[field.key] ?? '')}`).join(', '));
  }
}
```

| `PdfCollection` | Meaning |
| --- | --- |
| `view` | `details` (a table), `tile` or `hidden`, the layout the author asked for |
| `initialDocument` | Name of the file a reader should show first |
| `fields` | The schema in display order: `{ key, name, type, order, isVisible }` |
| `sort` | `{ key, isAscending }[]`, the sort order the author asked for |
| `items` | The document-level attachments, already sorted, each with `values` keyed by field |

`type` is `text`, `number` or `date` for values stored with each file, and `fileName`, `description`, `modified`, `created`, `size` or `compressedSize` for columns taken from the file itself. A value is a string, a number or a `Date`; a value with a prefix (for example a currency) is returned as one string, and sorting uses the value without the prefix.

Portfolios are read, not written: there is no method to create a collection or to edit its schema or item values. Attachments you add to a portfolio appear in `items` without item values. Folders and navigator layouts of Acrobat portfolios are ignored.

## In the viewer

The **Attachments** panel of the sidebar lists the files of the open document. Each row has an **Open**, a **Save** and, for document-level files in an editable document, a **Remove** button, all labelled with the file name. A row can be focused with the keyboard; `Enter` or a double click opens it.

For a portfolio the panel shows a short notice and a table with the visible schema columns instead of the plain list, in the sort order of the collection. When a portfolio is loaded and the host has not closed the sidebar (`isSidebarOpen: false`), has not removed the panel with `sidebarPanels`, and the viewer is not in its compact layout, the sidebar opens on the Attachments panel. A portfolio whose `view` is `hidden` does not do this.

### Opening a file in your application

The viewer cannot display a spreadsheet or an email by itself, so **Open** hands the file to the host through the `attachmentOpen` event:

```ts
viewer.on('attachmentOpen', (file) => {
  if (file.mimeType === 'text/csv') console.info(new TextDecoder().decode(file.data));
  else console.info(`${file.name}: ${file.size} bytes of ${file.mimeType}`);
});

const wasFound = viewer.openAttachment('lane-rates.csv');
```

| `AttachmentOpenEvent` | Meaning |
| --- | --- |
| `name`, `mimeType`, `size` | The file name, its media type (from the file, otherwise from the extension) and its size in bytes |
| `data` | The bytes of the file |
| `source` | `document` or `annotation` |
| `pageIndex` | The page of the annotation, for `source: 'annotation'` |
| `relationship`, `description` | Present when the file has them |

The event fires from the Open button, from `Enter` or a double click on a row, from **Open attachment** in the menu of a file attachment annotation, and from `viewer.openAttachment(name)`, which returns `false` when no attachment has that name. Nothing else happens when there is no listener: the viewer never opens a file in the browser on its own account. **Save** and **Download attachment** still download the file.

When the viewer is created with `tabs: true`, PDF attachments, and `.msg` and `.eml` attachments unless `convertMail` is `false`, also offer **Open in a new tab**, which loads the attachment as a document in the viewer itself.

### Attaching by drag and drop

Files dragged onto the Attachments panel are added as document-level attachments, several at once if you drop several. The panel is outlined while a file is over it, and the result is announced to screen readers. The drop is handled by the panel alone, so it does not trigger the "drop a PDF to open it" behaviour of `allowFileDrop`. In a read-only viewer, or when the document's permissions do not allow changing it, the drop is refused and the reason is announced, exactly as for the **Attach a file** button.

### From code

```ts
declare const ratesBytes: Uint8Array;

await viewer.addAttachment({ name: 'lane-rates.csv', data: ratesBytes, relationship: 'Data' });
console.info(viewer.getAttachments().map((file) => file.name));
console.info(viewer.getCollection()?.fields.map((field) => field.name));
await viewer.removeAttachment('lane-rates.csv');
```

## Limits

- **The file is stored, not understood.** There is no preview of Office documents, archives or other formats; use `attachmentOpen` to show them in a component of your own. Email attachments are the exception: they can be converted and opened, see [Email messages](https://docs.birchui.com/pdf/email.md).
- **MD5 only.** The checksum is the one the PDF format defines. It is not a signature. Sign the document if you need to prove that an attachment was not replaced.
- **An incremental save keeps removed files in the earlier revision.** `removeAttachment` takes the file out of the document, but its bytes are only gone from the saved file after `save({ mode: 'full' })`.
- **Attachments are held in memory**, once in the session and once more while saving. Very large files (hundreds of megabytes) are better linked than embedded.
- **Encrypted documents** encrypt attachments with the rest of the file. Encrypting only the attachments (`EFF`), and the `EncryptedPayload` wrapper documents of PDF 2.0, are not produced.
- **Portfolios are read-only**, as described above, and folders are not shown.
- **Files attached to other objects** (a page, a structure element or an XObject through their own `/AF` arrays) are not listed unless they are also in the embedded files name tree or belong to a file attachment annotation.
- **Related-files arrays (`/RF`) and non-embedded file references** (a path or URL without embedded data) are ignored.
