# Blazor PDF Viewer

URL: https://flexcoreui.com/demo/pdf-viewer  
Section: Reports  
Controls: PdfViewerControl  
Keywords: PDF viewer, PDF annotation, PDF forms, pdf.js Blazor

View, search, annotate and fill PDFs inside a Blazor page with a bundled pdf.js, and get the edited file back as bytes; nothing leaves the page.

## Documentation

### Params

| Name | Type | Default | Description |
|---|---|---|---|
| DocumentBytes | byte[]? | null | The document as bytes. A different array instance reloads; while bytes are present Url is ignored. |
| Url | string? | null | Fetched by the browser, so a relative path resolves against the page. A failed request is reported through Error. |
| Password | string? | null | Password for an encrypted file. A change reloads the document. |
| FileName | string | "document.pdf" | Name of the downloaded file. A file picked with Open PDF replaces it with its own name. |
| Height | string | "600px" | Height of the body under the two toolbars: the Details pane and the page viewport. |
| ShowBookmarks | bool | true | Lists the document outline in the Details pane; an entry with an internal destination jumps to its page, one without is shown disabled. |
| AllowOpen | bool | true | Shows the Open PDF picker in the toolbar. |
| AllowAnnotations | bool | true | Shows Highlight selection and Add note. Highlights and notes are kept by the viewer, listed in the Details pane and written into the file on Download, Print and SaveAsync. |
| AllowFormFilling | bool | true | Lists the form fields in the Details pane as text boxes, checkboxes and dropdowns. An edit re-renders the page with the new value; edited fields are written into the file on Download, Print and SaveAsync. Read-only fields are listed but not editable. |
| MaxFileSize | long | 50*1024*1024 | Upper bound in bytes for a picked file, DocumentBytes, a fetched Url and the stream SaveAsync reads back. Larger files are refused with "PDF exceeds MaxFileSize." |

### Events

| Name | Type | Description |
|---|---|---|
| Loaded | PdfDocumentInfo | After a document has opened and its first page rendered: page count, form fields and bookmarks. |
| Error | string | The first line of a load or edit failure; the same text is shown under the toolbars. |
| PageChanged | int | After the page changes by button, bookmark, search hit or GoToPageAsync. Zoom and rotation do not raise it. |
| SearchChanged | PdfSearchState | After Find, Next match, Previous match, a hit in the Details pane or Clear search, with the full PdfSearchState. |

### Methods

| Name | Type | Description |
|---|---|---|
| GoToPageAsync(int page) | Task | Shows that page, clamped to the document, and raises PageChanged. |
| SetZoomAsync(double zoom) | Task | Sets the zoom factor, clamped to 0.25 to 4. |
| FindAsync() | Task | Searches for the text in the search box with the current Match case setting. |
| SearchTextAsync(string query, bool matchCase = false) | Task | Searches every page for the literal text, selects the first hit, opens the Details pane and raises PageChanged and SearchChanged. |
| SearchNextAsync() / SearchPreviousAsync() | Task | Move to the next or previous hit, wrapping round at the ends. |
| GoToSearchMatchAsync(int index) | Task | Jumps to that hit; an index outside the list does nothing. |
| CancelTextSearchAsync() | Task | Clears the query, the hits and the highlights. |
| DownloadAsync() | Task | Downloads the file with the edits applied, under FileName. |
| PrintAsync() | Task | Prints the file with the edits applied through a hidden frame. |
| SaveAsync() | Task<byte[]> | Returns the file with the edits applied as bytes on the server, read as a stream up to MaxFileSize. Throws when no document is open. |
| OpenAsync(byte[] bytes, string? name = null) | Task | Opens bytes supplied by code, optionally renaming the file. |

### State

| Name | Type | Default | Description |
|---|---|---|---|
| Page | int | 1 | The page on show, from 1. |
| PageCount | int | 0 | Pages in the open document; 0 while none is open. |
| Zoom | double | 1 | The zoom factor; the toolbar moves it in steps of 0.25. |
| Busy | bool | false | True while the viewer loads, renders, searches or saves. |
| ErrorMessage | string? | null | The last failure, or null. |
| Bookmarks | IReadOnlyList<PdfBookmark> |  | The outline the document was opened with. |
| SearchState | PdfSearchState |  | The current query, hits and position. |

### Info

| Name | Type | Default | Description |
|---|---|---|---|
| Pages | int | 0 | Number of pages. |
| Fields | List<PdfFormField> | [] | The form fields found by the renderer. |
| Bookmarks | List<PdfBookmark> | [] | The top-level outline entries, each with its children. |

### Field

| Name | Type | Default | Description |
|---|---|---|---|
| Name | string | "" | The field's fully qualified name. |
| Type | string | "" | text, checkbox, combobox, listbox or radiobutton as the renderer reports it; any other type is listed read-only. |
| TextValue | string | "" | The text or the selected option. |
| BoolValue | bool | false | A checkbox's state. |
| Options | List<string> | [] | The choices of a dropdown or list; for a radio group, the export values. |
| ReadOnly | bool | false | True for read-only fields, multi-select lists and unsupported types. |
| Dirty | bool | false | True once edited in the viewer; only dirty fields are written on save. |

### Bookmark

| Name | Type | Default | Description |
|---|---|---|---|
| Title | string | "" | The outline text. |
| Page | int? | null | The target page, or null for a grouping entry or an external destination. Links and actions in the document are never followed. |
| Children | List<PdfBookmark> | [] | Nested entries. |

### Keys

| Name | Description |
|---|---|
| Enter in the search box | Runs the search. |
| Escape in the search box | Clears the search. |

### Css

| Name | Description |
|---|---|
| fx-pdf-viewer | The root element; CssClass is added here. |
| fx-pdf-body | The area under the toolbars that takes Height. |
| fx-pdf-sidebar | The Details pane: fx-pdf-bookmarks for the outline, fx-pdf-search-result per hit, fx-pdf-field per form field. |
| fx-pdf-viewport | The scrolling page area; fx-pdf-page holds the canvas, the fx-pdf-text text layer and the fx-pdf-search-layer. |
| fx-pdf-match | A search hit in the text or search layer; the current one also has fx-pdf-active-match. |
| fx-pdf-search-status | The "n of m matches" text in the search toolbar. |
| fx-pdf-error | The error line under the toolbars. |

## Examples

### Viewer

```razor
@using Fx.ControlKit.Pdf

<PdfViewerControl @ref="_viewer" Url="pdf-viewer-sample.pdf" FileName="flexcore-sample.pdf" Height="560px" Error="e => _saved = e" />
<p class="result">@_saved</p>
```

```csharp
private PdfViewerControl? _viewer;

private string _saved = "Nothing saved yet.";

private async Task SaveToHostAsync()
{
    if (_viewer is null) return;
    var bytes = await _viewer.SaveAsync();
    _saved = $"Saved {bytes.Length:N0} bytes on the server, with the current field values, highlights and notes.";
}
```

### Reader

```razor
@using Fx.ControlKit.Pdf

<PdfViewerControl @ref="_reader"
                  DocumentBytes="@_document"
                  FileName="flexcore-sample.pdf"
                  AllowOpen="false"
                  AllowAnnotations="false"
                  AllowFormFilling="false"
                  ShowBookmarks="false"
                  Height="480px"
                  Loaded='info => _info = $"{info.Pages} pages, {info.Fields.Count} fields, {info.Bookmarks.Count} top-level bookmarks."'
                  PageChanged="p => _page = p"
                  SearchChanged="s => _search = s" />
<p class="result">@_info Page @_page. @SearchText</p>
```

```csharp
private PdfViewerControl? _reader;

private byte[] _document = [];

private string _info = "Loading…";

private int _page = 1;

private PdfSearchState? _search;

private string SearchText => _search is null || _search.Query.Length == 0
    ? "No search."
    : $"{_search.Matches.Count} matches for '{_search.Query}', at {_search.CurrentIndex + 1}.";

protected override void OnInitialized() => _document = File.ReadAllBytes(Path.Combine(Env.WebRootPath, "pdf-viewer-sample.pdf"));
```

