Skip to main content

PdfViewer control

PdfViewer displays PDF documents in your Avalonia application. It is a complete reader out of the box, requiring only a document source to be set. The viewer includes many common PDF tools and functions, such as page thumbnails, zoom and view modes, text selection and search, form filling, bookmarks, native printing, and more.

info

This control is available as part of Avalonia Pro or higher.

When to use​

Use PdfViewer to show PDF documents inside your app. You can choose to enable or disable each tool and menu item, meaning it can work as a read-only viewer or an interactive editor.

Requirements​

  • .NET 10 or later.
  • Avalonia 12.0 or later.
  • An Avalonia Pro or Enterprise license that covers the PDF Viewer.
  • Windows, macOS, Linux (x64 and arm64), iOS 15 or later, Android API 23 or later, or WebAssembly.

Dependencies​

PdfViewer renders with PDFium, which is bundled as a native library through the bblanchon.PDFium.* NuGet packages. Each target framework depends only on the packages for its own platforms.

TargetPackages
net10.0 (Windows, macOS, Linux)Avalonia, AvaloniaUI.Licensing, bblanchon.PDFium.Win32, bblanchon.PDFium.macOS, bblanchon.PDFium.Linux
net10.0-iosAvalonia, AvaloniaUI.Licensing, bblanchon.PDFium.iOS
net10.0-androidAvalonia, Avalonia.Android, AvaloniaUI.Licensing, bblanchon.PDFium.Android
net10.0-browserAvalonia, AvaloniaUI.Licensing, bblanchon.PDFium.WebAssembly

PDFium is licensed under the BSD 3-Clause License.You must include its notice in your application's third-party attributions.

Getting started​

  1. Install the Avalonia.Controls.PdfViewer NuGet package by running dotnet add package. Add it to the project that contains your views and to each application head (desktop, iOS, Android, browser). This ensurea each head restores the required PDFium binaries for its own platform.
dotnet add package Avalonia.Controls.PdfViewer
  1. Reference the AvaloniaUI.Licensing package in each application head. Include your Avalonia license key in the executable project file (.csproj). Your license key is available from the Avalonia portal.
<ItemGroup>
<PackageReference Include="AvaloniaUI.Licensing" Version="3.1.2" />
</ItemGroup>
<ItemGroup>
<AvaloniaUILicenseKey Include="YOUR_LICENSE_KEY" />
</ItemGroup>
tip

For multi-project solutions, you can store your licence key in an environment variable or a shared props file to avoid duplication.

Reference the TreeDataGrid fluent theme via a StyleInclude in your App.axaml file. This adds the resources needed to render the control.

  1. Reference one of the two available PdfViewer themes via a StyleInclude in your App.axaml file. Without a theme, the control cannot render. Default.axaml has its own palette. Fluent.axaml follows the host's FluentTheme.
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.PdfViewer/Themes/Default.axaml" />
</Application.Styles>

For more information on installing Avalonia Pro controls, see Installing Avalonia Pro.

Basic usage​

PdfViewer lives in the Avalonia.Controls namespace. Its package name is Avalonia.Controls.PdfViewer.

<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pdf="using:Avalonia.Controls"
Width="1000" Height="700">

<pdf:PdfViewer x:Name="Viewer"
Source="/path/to/document.pdf"
ViewMode="Continuous"
SidebarMode="Thumbnails" />

</Window>

Setting Source loads the document. It can be set before the viewer is attached to the visual tree, for example from a view model constructor.

Namespaces​

NamespaceContents
Avalonia.ControlsPdfViewer, its enums, its event args and PdfViewerStrings.
Avalonia.Controls.Pdf.CoreData types: PdfAnnotationColor, PdfBookmark, PdfSearchResult, PdfMetadata, PdfPermissions, SearchOptions, PdfLinkDestination.
Avalonia.Controls.Pdf.ServicesPrint and share types: PrintOptions, IPrintService, ShareOptions, IShareService.

Properties​

Document, view and zoom​

PropertyTypeDefaultDescription
Sourcestring?nullPath to the PDF file. Setting it loads the document.
DocumentSourceobject?nullFlexible source. Can be a file path string, a Stream, or a byte[].
Passwordstring?nullPassword for encrypted PDFs.
CurrentPageint0Current page number. 1-based when a document is open, 0 when not. Coerced to a range of 1 to PageCount.
ZoomLeveldouble1.0Zoom level. 1.0 is 100%.
ZoomModePdfZoomModeFitPageManual, FitWidth, FitPage, FitHeight or ActualSize.
MinZoomdouble0.05Lower zoom bound.
MaxZoomdouble5.0Upper zoom bound.
ZoomStepdouble0.0Increment applied by ZoomIn and ZoomOut. 0 uses the built-in adaptive step.
ViewModePdfViewModeContinuousSinglePage, Continuous, TwoPages or TwoPagesContinuous.
PageRenderBufferint2Pages decoded on each side of the viewport in continuous mode. Only accepts values from 0 to 10.
PageRetentionBufferint4Pages kept decoded on each side before eviction. Only accepts values from 0 to 20.
MaxRenderScaledouble2.0Upper bound on device pixels per DIP used when decoding a page. Coerced to 1 to 4.
VerticalScrollOffsetdoubleCurrent vertical scroll offset.
PropertyTypeDefaultDescription
SidebarModeSidebarModeThumbnailsNone, Thumbnails, TableOfContents or Bookmarks.
IsSidebarVisiblebooltrueShows or hides the sidebar.
SidebarWidthdouble210Sidebar width in device-independent pixels.
SidebarPlacementSidebarPlacementAutoAuto, Overlay or Offset. Auto displays as overlay in mobile layout, and offset in desktop layout.
SidebarSelectionBrushIBrush?nullBrush of the selected thumbnail and outline entry. null uses the theme's PdfThumbnailSelectedBorder resource.
IsTableOfContentsEnabledbooltrueEnables the outline tab in the sidebar.
IsBookmarksEnabledbooltrueEnables the bookmarks tab in the sidebar.
ShowBookmarkIndicatorsbooltrueDraws a ribbon on bookmarked pages and thumbnails.
IsToolbarVisiblebooltrueShows or hides the toolbar.
IsMoreOptionsVisiblebooltrueShows or hides the toolbar's More Options menu, which contains print, share, and view modes.
IsPrintVisiblebooltrueEnables Print in the More Options menu. Always hidden when nothing can print.
IsShareVisiblebooltrueEnables Share in the More Options menu. Always hidden when nothing can share.
IsOpenVisibleboolfalseEnables Open in the More Options menu.
IsSaveVisibleboolfalseEnables Save in the More Options menu. Always hidden while AllowDocumentSaving is false.
IsSaveAsVisibleboolfalseEnables Save As in the More Options menu.
PrintServiceIPrintService?unsetPrint implementation. Unset uses the built-in platform service. null disables it.
ShareServiceIShareService?unsetShare implementation. Unset uses the built-in platform service. null disables it.
ToolbarLayoutModePdfToolbarLayoutModeAutoAuto picks the layout from the platform and width. Mobile and Desktop force one.
IsMobileLayoutboolWhether the compact mobile layout is active. Set by the control: true on iOS and Android, and on any platform when the control is narrower than 500 device-independent pixels.

Each tool has its own visibility property, allowing you to decide exactly which tools the toolbar offers. See Toolbar visibility for the full list of properties.

Capabilities and permissions​

PropertyTypeDefaultDescription
IsReadOnlyboolfalseDisables annotations and form editing when true. Does not affect saving, which is controlled by AllowDocumentSaving (see below).
AllowTextSelectionbooltrueEnables text selection and copy.
AllowAnnotationEditingbooltrueEnables creating and editing annotations.
AllowFormEditingbooltrueEnables interactive form field editing.
AllowDocumentSavingbooltrueEnables saving. Gates SaveCommand and SaveAsync.
RespectDocumentPermissionsbooltrueHonors the document's permission flags for annotation, form filling, copying and printing. A document opened with its owner password is always unrestricted.
AutoSaveboolfalseSaves back to Source after each edit. Requires AllowDocumentSaving to be true.
EnableKeyboardShortcutsbooltrueHandles the viewer's built-in keyboard shortcuts. Set false to allow keystrokes to reach the host's own commands.
IsArrowKeyNudgeEnabledbooltrueIf enabled, annotations can be moved with the arrow keys when selected.
SearchQuerystring?nullText in the toolbar search box.
SearchMatchCaseboolfalseWhether search should match uppercase/lowercase.
SearchMatchWholeWordboolfalseWhether search should match whole words.
StringsPdfViewerStringsPdfViewerStrings.DefaultUser-facing text. See Localization.

State​

These properties are read-only but can be bound.

PropertyTypeDescription
PageCountintNumber of pages in the loaded document.
HasDocumentboolWhether a document is open.
IsLoadingbooltrue while a document is loading.
IsDirtybooltrue while the document has unsaved edits. Cleared by a successful save or by loading another document.
IsSidebarOpenbooltrue when the sidebar is expanded.
HasOutlinebooltrue when the document has a table of contents.
HasBookmarksbooltrue when the document has bookmarks.
HasSelectionbooltrue when text is selected.
SelectedTextstring?The current text selection.
SearchResultsIReadOnlyList<PdfSearchResult>?Results of search.
SearchResultCountintNumber of search matches.
CurrentSearchResultIndexintIndex of the highlighted search match.
ErrorMessagestring?Last error message. Shown as a dismissible banner over an open document, or as the canvas state after a failed load. Can be cleared with ClearError().
MetadataPdfMetadata?Document metadata, such as title and author.
PermissionsPdfPermissions?Document permission flags.
CanEditAnnotationsbooltrue when annotations can be created or edited.
CanPrintbooltrue when a document is open and a print service or handler exists.
CanSharebooltrue when a document is open and a share service or handler exists.
CanUndoboolUndo history has an entry that can be applied.
CanRedoboolRedo history has an entry that can be applied.

Commands​

All commands are ICommand and update CanExecute as document and selection states change.

CommandDescription
ZoomInCommand, ZoomOutCommand, ResetZoomCommandAdjust the zoom.
FitWidthCommand, FitPageCommandApply a fit mode.
NextPageCommand, PreviousPageCommand, GoToPageCommandNavigate between pages.
SelectAllCommandSelect all text on the current page.
CopyCommandCopy the selection.
OpenCommand, SaveCommand, SaveAsCommandFile operations. See Loading and saving.
PrintCommandPrint the document, See Printing and sharing.
ShareCommandShare the document, See Printing and sharing.
SetToolCommandArms an annotation tool. The parameter is a PdfViewerTool value or its name.
ToggleBookmarkCommand, AddBookmarkCommand, RemoveBookmarkCommandChange the bookmark on a page. The parameter is a 1-based page number, else the current page.
DismissErrorCommandClears ErrorMessage.

Binding commands to controls​

You can bind commands to your own controls (e.g., a button) if you wish to customize the UI beyond the built-in toolbar. For example:

<Button Content="Fit width" Command="{Binding #Viewer.FitWidthCommand}" />
<Button Content="Highlight" Command="{Binding #Viewer.SetToolCommand}" CommandParameter="Highlight" />

Events​

EventArgsDescription
DocumentLoadedPdfDocumentLoadedEventArgsDocument finished loading. Args include PageCount and Metadata.
DocumentClosedEventArgsDocument was closed.
LoadErrorPdfLoadErrorEventArgsDocument loading failed.
AnnotationErrorPdfAnnotationErrorEventArgsAnnotation operation failed. Args include Operation and Exception.
AnnotationAddedPdfAnnotationEventArgsAnnotation was added.
PageChangedPdfPageChangedEventArgsCurrent page changed. Args include OldPage and NewPage, 1-based.
ZoomChangedPdfZoomChangedEventArgsZoom level changed.
PageRenderedPdfPageRenderedEventArgsPage finished rendering.
SearchCompletedPdfSearchCompletedEventArgsSearch finished.
LinkClickedPdfLinkClickedEventArgsLink was clicked. See Links.
BookmarksChangedEventArgsBookmark was added or removed.
UndoRedoStateChangedEventArgsValue(s) of CanUndo or CanRedo changed.
PrintRequestedPdfPrintRequestedEventArgsRaised before printing. Set Handled to print in the app instead of the platform service.
ShareRequestedPdfShareRequestedEventArgsRaised before sharing. Set Handled to share in the app instead of the platform service.
OpenRequestedPdfOpenRequestedEventArgsRaised before going to the built-in file dialog. Set Handled to open in the app.
SaveAsRequestedPdfSaveAsRequestedEventArgsRaised before going to the built-in save dialog. Set Handled to write the PDF in the app.

Threading​

Every public member of PdfViewer must be called on the UI thread. The *Async members throw if called from another thread. They do not block the UI while a page is decoding.

PDFium itself is single-threaded, so several viewers in one process share one pipeline.

See also​