Skip to main content

PdfViewer control

PdfViewer displays PDF documents in your Avalonia application. It is a complete reader out of the box: set a source and you have a toolbar and sidebar, page thumbnails and a document outline, page navigation, zoom and view modes, text selection and search, a full annotation toolset with undo and redo, form filling, bookmarks, and native printing and sharing. Each of these can be hidden or disabled, and everything is available from code as well as through the built-in UI. The same control and package run on Windows, macOS, Linux, iOS, Android and WebAssembly.

info

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

When to use

Use PdfViewer to show PDF documents inside your app. Every tool and menu entry can be hidden or disabled, so it works as a plain read-only viewer or as a full annotation editor.

To render a page as an image outside the viewer, for example for a thumbnail in a file list, use RenderPageToImageAsync.

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

The package 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, so an app head restores nothing it does not need.

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. 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), so 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 and include your Avalonia license key in the executable project file (.csproj). Your license key is available from the Avalonia portal. The control throws AvaloniaLicensingException on first use if the key is missing or does not cover the PDF Viewer.
<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.

  1. Reference one of the two themes via a StyleInclude in your App.axaml file. Without a theme the control renders nothing. Default.axaml has its own palette and works under any host theme. Fluent.axaml follows the host's FluentTheme accent and theme variant.
<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

The control lives in the Avalonia.Controls namespace. Avalonia.Controls.PdfViewer is the package and assembly name, so map the namespace with an xmlns prefix in XAML.

<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: a file path string, a Stream, or a byte[].
Passwordstring?nullPassword for encrypted PDFs.
CurrentPageint0Current page number. 1-based once a document is open, 0 while none is. Coerced to the range 1 to PageCount.
ZoomLeveldouble1.0Zoom level, from MinZoom to MaxZoom. 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. Clamped to 0 to 10.
PageRetentionBufferint4Pages kept decoded on each side before eviction. Clamped to 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 DIPs.
SidebarPlacementSidebarPlacementAutoAuto (overlay in the mobile layout, offset on desktop), Overlay or Offset.
SidebarSelectionBrushIBrush?nullBrush of the selected thumbnail and outline entry. null uses the theme's PdfThumbnailSelectedBorder resource.
IsTableOfContentsEnabledbooltrueOffers the outline tab in the sidebar.
IsBookmarksEnabledbooltrueOffers 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 (print, share, view modes).
IsPrintVisiblebooltrueOffers Print in the More Options menu. Hidden anyway when nothing can print.
IsShareVisiblebooltrueOffers Share in the More Options menu. Hidden anyway when nothing can share.
IsOpenVisibleboolfalseOffers Open at the top of the More Options menu.
IsSaveVisibleboolfalseOffers Save in the More Options menu. Hidden while AllowDocumentSaving is false.
IsSaveAsVisibleboolfalseOffers Save As in the More Options menu.
PrintServiceIPrintService?platformPrint implementation. Unset uses the built-in platform service, null disables it.
ShareServiceIShareService?platformShare implementation, with the same semantics as PrintService.
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 DIPs. Use ToolbarLayoutMode to force a layout.

The visibility of each annotation tool is controlled by its own property. See Annotations.

Capabilities and permissions

PropertyTypeDefaultDescription
IsReadOnlyboolfalseDisables annotation and form editing in one switch. Saving is gated separately by AllowDocumentSaving.
AllowTextSelectionbooltrueEnables text selection and copy.
AllowAnnotationEditingbooltrueEnables creating and editing annotations.
AllowFormEditingbooltrueEnables interactive form field editing.
AllowDocumentSavingbooltrueEnables saving. Gates SaveCommand and SaveAsync.
RespectDocumentPermissionsbooltrueHonours the document's own permission flags. Annotation editing, form filling, text selection and printing are each withheld when the document forbids them. A document opened with its owner password is unrestricted.
AutoSaveboolfalseSaves back to Source after each edit. Requires AllowDocumentSaving.
EnableKeyboardShortcutsbooltrueHandles the viewer's built-in keyboard shortcuts. Set false so those keystrokes reach the host's own commands.
IsArrowKeyNudgeEnabledbooltrueWith an annotation selected, the arrow keys move it instead of navigating.
SearchQuerystring?nullText in the toolbar search box.
SearchMatchCaseboolfalseCase-sensitive option of the toolbar search box.
SearchMatchWholeWordboolfalseWhole-word option of the toolbar search box.
StringsPdfViewerStringsPdfViewerStrings.DefaultEvery user-facing text. See Localization.

State

These properties are read-only and bindable.

PropertyTypeDescription
PageCountintNumber of pages in the loaded document.
HasDocumentboolWhether a document is open.
IsLoadingbooltrue while a document is loading.
IsDirtyboolThe document has edits not yet written. Cleared by a successful save and by loading another document.
IsSidebarOpenbooltrue when the sidebar is expanded.
HasOutlineboolThe document has a table of contents.
HasBookmarksboolThe document has user bookmarks.
HasSelectionboolText is currently selected.
SelectedTextstring?The current text selection.
SearchResultsIReadOnlyList<PdfSearchResult>?Results of the last search.
SearchResultCountintNumber of search matches.
CurrentSearchResultIndexintIndex of the highlighted match.
ErrorMessagestring?Last error message. Shown as a dismissible banner over an open document, or as the canvas state after a failed load. Clear it with ClearError().
MetadataPdfMetadata?Document metadata such as title and author.
PermissionsPdfPermissions?Document permission flags.
CanEditAnnotationsboolAnnotations can be created and edited right now.
CanPrintboolA document is open and a print service or handler exists.
CanShareboolA document is open and a share service or handler exists.
CanUndoboolThe undo history has an entry to apply.
CanRedoboolThe redo history has an entry to apply.

Commands

All commands are ICommand and update CanExecute as document and selection state changes. Bind them from your own buttons if you hide the built-in toolbar.

CommandDescription
ZoomInCommand, ZoomOutCommand, ResetZoomCommandAdjust the zoom.
FitWidthCommand, FitPageCommandApply a fit mode.
NextPageCommand, PreviousPageCommand, GoToPageCommandNavigate between pages.
SelectAllCommand, CopyCommandSelect all text on the current page, copy the selection.
OpenCommand, SaveCommand, SaveAsCommandFile operations. See Loading and saving.
PrintCommand, ShareCommandSee 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.
<Button Content="Fit width" Command="{Binding #Viewer.FitWidthCommand}" />
<Button Content="Highlight" Command="{Binding #Viewer.SetToolCommand}" CommandParameter="Highlight" />

Events

EventArgsDescription
DocumentLoadedPdfDocumentLoadedEventArgsA document finished loading. Args include PageCount and Metadata.
DocumentClosedEventArgsThe document was closed.
LoadErrorPdfLoadErrorEventArgsDocument loading failed.
AnnotationErrorPdfAnnotationErrorEventArgsAn annotation operation failed. Args include Operation and the underlying Exception.
AnnotationAddedPdfAnnotationEventArgsAn annotation was added.
PageChangedPdfPageChangedEventArgsThe current page changed. Args include OldPage and NewPage, 1-based.
ZoomChangedPdfZoomChangedEventArgsThe zoom level changed.
PageRenderedPdfPageRenderedEventArgsA page finished rendering.
SearchCompletedPdfSearchCompletedEventArgsA search finished.
LinkClickedPdfLinkClickedEventArgsA link was clicked. See Links.
BookmarksChangedEventArgsA user bookmark was added or removed.
UndoRedoStateChangedEventArgsCanUndo 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 the built-in file picker. Set Handled to open in the app.
SaveAsRequestedPdfSaveAsRequestedEventArgsRaised before the built-in save picker. 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 decode pipeline.

See also