
Syncfusion Uwp Pdf Viewer
- 1 installs
- 1 repo stars
- Updated July 6, 2026
- syncfusion/pdf-viewer-sdk-skills
Implements the Syncfusion UWP SfPdfViewerControl for native Windows PDF viewing, annotations, text search, ink signatures, printing, and navigation.
About
Generates code for the Syncfusion UWP SfPdfViewerControl to view, annotate, search, and print PDFs in native Windows apps. A developer uses it when building PDF viewing and annotation workflows in UWP apps.
- Uses the Windows.Data.Pdf engine with optional PDFium renderer
- Covers annotations, ink signatures, bookmark and hyperlink navigation
Syncfusion Uwp Pdf Viewer by the numbers
- 1 all-time installs (skills.sh)
- Ranked #121 of 153 .NET & C# skills by installs in the Skillselion catalog
- Data as of Jul 8, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/pdf-viewer-sdk-skills --skill syncfusion-uwp-pdf-viewerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 1 |
| Last updated | July 6, 2026 |
| Repository | syncfusion/pdf-viewer-sdk-skills ↗ |
What it does
Implements the Syncfusion UWP SfPdfViewerControl for native Windows PDF viewing, annotations, text search, ink signatures, printing, and navigation.
Files
Implementing UWP PDF Viewer (SfPdfViewerControl)
The Syncfusion SfPdfViewerControl is a native UWP control for viewing, annotating, searching, and printing PDF documents. It uses the Windows rendering engine (Windows.Data.Pdf) by default and supports an optional PDFium renderer.
Security Notice ⚠️
When loading PDFs from untrusted or user-provided sources, always validate hyperlinks and content before allowing navigation. PDFs can contain malicious hyperlinks that may direct users to untrusted websites or perform unintended actions. Always implement hyperlink validation using the HyperlinkPointerPressed event to inspect and authorize navigation targets before allowing them. See references/bookmarks-and-hyperlinks.md for validation code examples.
When to Use This Skill
Use this skill when you need to:
- View and navigate PDF documents in UWP applications
- Load PDFs from streams, StorageFile objects, or byte arrays
- Add and manage annotations (highlight, underline, strikethrough, ink, shapes, free text, popup, stamp)
- Search and select text within PDF documents
- Navigate pages, bookmarks, and hyperlinks (with proper validation for untrusted sources)
- Print PDF documents with custom quality and preview settings
- Create custom toolbars wired to PDF Viewer commands
- Configure zoom, view modes, scrollbar, and progress ring
- Localize the viewer UI
- Export PDF pages as images or use the PDFium custom renderer
Component Overview
SfPdfViewerControl is a comprehensive PDF viewing and management control for UWP with these capabilities:
- Document Management: Load from PdfLoadedDocument, Stream, or StorageFile (sync and async with CancellationToken); save with annotations; unload and dispose
- Annotations: Text markup (highlight, underline, strikethrough), shape (rectangle, ellipse, line), ink with Windows Ink Canvas support, popup (sticky note), free text, free text callout, and custom stamp annotations
- Text Operation: Text selection with color customization, synchronous and asynchronous text search with next/previous navigation
- Navigation & UI: Page navigation commands, bookmarks, hyperlink handling, zoom/view modes, thumbnail view, separate desktop and mobile toolbar layouts, scrollbar and progress ring customization
- Utilities & Advanced: Export pages as images (GetPage, GetPages, ExportAsImage), vertical/horizontal offset access, PDFium custom renderer via IPdfRenderer interface, page number display
Documentation and Navigation Guide
Getting Started & Setup
📄 Read: references/getting-started.md
- Covers required assemblies, NuGet packages, adding the control via XAML or code, ItemsSource binding, and the DocumentLoaded event
- Explains synchronous and asynchronous loading methods, page count access, saving (Save/SaveAsync), unloading, and disposing
Document Operations
📄 Read: references/viewing-pdf.md
- Describes loading PDFs from PdfLoadedDocument, Stream, and StorageFile objects using both sync and async approaches
- Covers CancellationToken support for async loading, saving with annotations, and viewer unload/dispose patterns
Page Navigation & Viewing
📄 Read: references/page-navigation.md
- Explains programmatic page navigation, built-in navigation commands (FirstPage, LastPage, NextPage, PreviousPage), and XAML command binding
- Covers the PageChanged event, page count, page gap, offset collection, and toggling the page number display
Magnification & View Modes
📄 Read: references/magnification.md
- Covers zoom control via ZoomTo, increase/decrease zoom commands, and view mode options (FitWidth, Normal, OnePage)
- Explains MinimumZoomPercentage, thumbnail view toggle, and reading the current zoom value
Text Search
📄 Read: references/text-operations.md
- Explains synchronous and asynchronous text search, forward/backward result navigation, and SearchNextCommand/SearchPreviousCommand
- Covers GetTextCoordinates for retrieving the page positions of all text matches
Text Selection
📄 Read: references/text-operations.md
- Describes enabling text selection, customizing the selection highlight color, and the TextSelectionCompleted event
- Covers copying selected text to the clipboard
Annotations
📄 Read: references/annotations.md
- Covers all supported annotation types: text markup (highlight, underline, strikethrough), shapes (rectangle, ellipse, line), ink with Windows Ink Canvas, popup, free text, free text callout, and custom stamps
- Explains annotation events (Added, Tapped, Selected, Removed, MovedOrResized), deleting annotations, AnnotationCollection, undo/redo, and the IsDocumentEdited property
Printing
📄 Read: references/printing.md
- Explains the Print method, PrintCommand, and async printing with CancellationToken support
- Covers QualityFactor, customizing or disabling the print preview dialog, and setting the document name via PrinterSettings
Bookmarks & Hyperlinks
📄 Read: references/bookmarks-and-hyperlinks.md
- Explains navigating to bookmarks via GoToBookmark and retrieving the bookmark collection from PdfLoadedDocument
- 🔒 REQUIRED - Hyperlinks Validation: Provides essential code examples for inspecting and validating hyperlinks via
HyperlinkPointerPressedevents. Always validate hyperlink sources from untrusted PDFs before allowing navigation to prevent malicious redirects and injection attacks. See the reference document for secure implementation patterns.
Localization
📄 Read: references/localization.md
- Covers setting the default language in the app manifest and adding .resw resource files for UI string localization
- Explains supported resource file names and changing the context menu language
Gesture Events & Interaction
📄 Read: references/utilities.md
- Covers pointer events on hyperlinks (HyperlinkPointerPressed, HyperlinkPointerMoved) for custom interaction handling
- Explains using the PageChanged and DocumentLoaded events to drive post-navigation and post-load workflows
Utilities & Advanced
📄 Read: references/utilities.md
- Covers exporting PDF pages as BitmapImage objects (GetPage, GetPages) and as image streams (ExportAsImage)
- Explains accessing vertical/horizontal scroll offsets, using the PDFium custom renderer via IPdfRenderer, and the ShowPageNumber and VerticalScrollBarWidth properties
Syncfusion UWP PDF Viewer — Skill
Overview
The syncfusion-uwp-pdf-viewer skill enables AI-assisted code generation for the Syncfusion UWP SfPdfViewerControl. It produces minimal, copy-pasteable C# and XAML code to embed, configure, and interact with PDF documents inside Universal Windows Platform (UWP) applications.
---
Compatibility
| Requirement | Version |
|---|---|
| .NET Framework | UWP (Universal Windows Platform) |
| Target Platform | Windows 10 (Build 1809) or later |
| Visual Studio | Visual Studio 2017 or later |
---
Skill Structure
syncfusion-uwp-pdf-viewer/
├── SKILL.md # Skill rules, routing, and code generation guidelines
├── README.md # This file
└── references/
├── getting-started.md # Minimal setup, XAML declaration, document loading
├── viewing-pdf.md # Load from Stream, PdfLoadedDocument, StorageFile
├── page-navigation.md # Navigate pages, commands, PageChanged event
├── magnification.md # Zoom control, view modes, thumbnail toggle
├── text-operations.md # Text search/selection, clipboard operations
├── annotations.md # Text markup, shapes, ink, popup, free text, stamps
├── printing.md # Print configuration, quality settings, preview
├── bookmarks-and-hyperlinks.md # Bookmark navigation, hyperlink validation (security)
├── localization.md # UI localization, resource files, language settings
└── utilities.md # Export pages, scroll offset, PDFium renderer---
Quick Start
1. Install NuGet Package
Install-Package Syncfusion.SfPdfViewer.UWP2. Add License Key (App.xaml.cs)
public App()
{
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY");
this.InitializeComponent();
}3. Add Control to XAML (MainPage.xaml)
<Page xmlns:syncfusion="using:Syncfusion.Windows.PdfViewer">
<Grid>
<syncfusion:SfPdfViewerControl x:Name="pdfViewer"/>
</Grid>
</Page>4. Load PDF Document
Option A: From Embedded Resource
using Syncfusion.Pdf.Parsing;
using System.Reflection;
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("PdfViewerApp.Assets.sample.pdf");
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(buffer);
pdfViewer.LoadDocument(loadedDocument);Option B: From File Picker
private async void LoadPdfButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.List;
picker.FileTypeFilter.Add(".pdf");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
pdfViewer.LoadDocument(file);
}
}Option C: Using Data Binding (ItemsSource)
<Page Loaded="Page_Loaded">
<Page.DataContext>
<local:PdfReportViewModel/>
</Page.DataContext>
<Grid>
<syncfusion:SfPdfViewerControl x:Name="pdfViewer"
ItemsSource="{Binding DocumentStream}"/>
</Grid>
</Page>5. Run the Application
F5---
Security Notice ⚠️
Always validate hyperlinks before allowing navigation when loading PDFs from untrusted sources.
pdfViewer.HyperlinkPointerPressed += (sender, args) =>
{
if (!IsUriTrusted(args.Uri))
{
args.Handled = true; // Block navigation
}
};See references/bookmarks-and-hyperlinks.md for complete validation examples.
---
Reference File Routing
Use the table below to find the correct reference file for any feature request.
Core Setup & Document Loading
| Reference File | Use When … |
|---|---|
getting-started.md | Initial setup, XAML declaration, NuGet packages, ItemsSource binding |
viewing-pdf.md | Loading from Stream, PdfLoadedDocument, StorageFile; saving, unloading, disposal |
Navigation & Viewing
| Reference File | Use When … |
|---|---|
page-navigation.md | Navigate to first/last/next/previous page, page commands, PageChanged event |
magnification.md | Zoom in/out, fit-to-width, fit-to-page, thumbnail view, view modes |
bookmarks-and-hyperlinks.md | Navigate bookmarks, validate hyperlinks (security), GoToBookmark method |
Text Operations
| Reference File | Use When … |
|---|---|
text-operations.md | Search text (sync/async), navigate results, text selection, clipboard copy, highlight color |
Annotations
| Reference File | Use When … |
|---|---|
annotations.md | Text markup (highlight, underline, strikethrough), free text callout, shapes, ink, popup notes, free text, stamps, undo/redo |
Document Actions
| Reference File | Use When … |
|---|---|
printing.md | Print configuration, quality factor, print preview customization, async printing |
Advanced Features
| Reference File | Use When … |
|---|---|
localization.md | Change UI language, add resource files, localize context menus |
utilities.md | Export pages as images, scroll offsets, PDFium renderer, page number display |
---
---
Available Features
The UWP PDF Viewer provides comprehensive document viewing and management capabilities:
| Feature | Description |
|---|---|
| Document Loading | Stream, PdfLoadedDocument, async loading with CancellationToken |
| Navigation | Page commands, bookmarks, hyperlinks (with validation) |
| Viewing | Zoom controls, view modes (FitWidth, Normal, OnePage), thumbnail view |
| Text Operations | Sync/async search, text selection, highlight color customization |
| Annotations | Text markup, shapes, ink (Windows Ink Canvas), popup, free text, stamps |
| Printing | Quality settings, print preview customization, async printing |
| Localization | Multi-language UI support with resource files |
| Advanced | Export pages as images, PDFium custom renderer, scroll offset access |
---
Example Prompts
- "Show me how to set up SfPdfViewerControl in UWP XAML"
- "How do I navigate to the next page in the PDF viewer?"
- "How do I search for text in a PDF document?"
- "How do I add a highlight annotation to selected text?"
- "How do I validate hyperlinks before allowing navigation?"
- "How can I customize the print preview dialog?"
---
Metadata
| Field | Value |
|---|---|
| Skill Name | syncfusion-uwp-pdf-viewer |
| Author | Syncfusion Inc |
| Version | 1.0.0 |
| Category | Document Viewing |
| Framework | UWP (Universal Windows Platform) |
| Reference Files | 10 |
Annotations in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
- Supported Annotation Types
- Annotation Events
- Global Annotation Settings
- Text Markup Annotations
- Shape Annotations
- Ink Annotations
- Popup Annotations
- Free Text Annotations
- Free Text Callout Annotations
- Custom Stamp Annotations
- Deleting Annotations
- Undo / Redo Annotation Changes
- Check If Document Is Edited
---
Supported Annotation Types
1. Text markup (Highlight, Underline, Strikethrough) 2. Shape (Rectangle, Ellipse, Line) 3. Ink 4. Popup (sticky note) 5. Free text 6. Free text callout 7. Custom stamp (any UIElement)
---
Annotation Events
All annotation events expose AnnotationProperties from the event args (except AnnotationMovedOrResized):
pdfViewer.AnnotationAdded += PdfViewer_AnnotationAdded;
pdfViewer.AnnotationTapped += PdfViewer_AnnotationTapped;
pdfViewer.AnnotationSelected += PdfViewer_AnnotationSelected;
pdfViewer.AnnotationDeselected+= PdfViewer_AnnotationDeselected;
pdfViewer.AnnotationRemoved += PdfViewer_AnnotationRemoved;
pdfViewer.AnnotationMovedOrResized += PdfViewer_AnnotationMovedOrResized;
private void PdfViewer_AnnotationAdded(object sender, AnnotationAddedEventArgs e)
{
if (e.AnnotationProperties is TextMarkupProperties)
{
TextMarkupProperties props = e.AnnotationProperties as TextMarkupProperties;
AnnotationMode mode = props.AnnotationType; // Highlight, Underline, etc.
Color color = props.Color;
double opacity = props.Opacity;
int pageNumber = props.PageNumber;
}
}
private void PdfViewer_AnnotationMovedOrResized(object sender,
AnnotationMovedOrResizedEventArgs e)
{
int newX = e.NewX; int newY = e.NewY;
int oldX = e.OldX; int oldY = e.OldY;
int newWidth = e.NewWidth; int newHeight = e.NewHeight;
int oldWidth = e.OldWidth; int oldHeight = e.OldHeight;
int pageNumber = e.PageNumber;
}Set Annotation Author
pdfViewer.AnnotationAdded += (s, e) =>
{
if (e.Annotation is IAnnotation)
e.Annotation.Author = "Syncfusion";
};---
Global Annotation Settings
// Disable annotation selection (read-only annotations)
pdfViewer.AnnotationSettings.IsReadOnly = true;
// Show or hide all annotations
pdfViewer.AnnotationVisibility = Visibility.Collapsed;
// Get all annotations in the document
var annotations = pdfViewer.AnnotationCollection;---
Text Markup Annotations
Supports: Highlight, Underline, Strikethrough
Enable / Disable via Command
// Enable highlight mode
pdfViewer.HighlightAnnotationCommand.Execute(true);
// Disable highlight mode
pdfViewer.HighlightAnnotationCommand.Execute(false);
// Same pattern for Underline and Strikethrough:
pdfViewer.UnderlineAnnotationCommand.Execute(true);
pdfViewer.StrikeoutAnnotationCommand.Execute(true);Customize Default Appearance
// Color (applies to newly added annotations only)
pdfViewer.HighlightAnnotationSettings.Color = Color.FromArgb(255, 255, 0, 0);
// Opacity (0.0 to 1.0)
pdfViewer.HighlightAnnotationSettings.Opacity = 0.5f;---
Shape Annotations
Supports: Rectangle, Ellipse, Line
Enable / Disable via Command
pdfViewer.RectangleAnnotationCommand.Execute(true); // Enable rectangle
pdfViewer.RectangleAnnotationCommand.Execute(false); // Disable
pdfViewer.EllipseAnnotationCommand.Execute(true);
pdfViewer.LineAnnotationCommand.Execute(true);Customize Default Appearance
// Stroke color
pdfViewer.RectangleAnnotationSettings.Color = Color.FromArgb(255, 255, 0, 0);
// Opacity
pdfViewer.RectangleAnnotationSettings.Opacity = 0.5f;
// Border thickness
pdfViewer.RectangleAnnotationSettings.Thickness = 5;Detect Property Changes
pdfViewer.ShapeEdited += PdfViewer_ShapeEdited;
private void PdfViewer_ShapeEdited(object sender, ShapeEditedEventArgs e)
{
double newThickness = e.NewThickness;
double oldThickness = e.OldThickness;
Color newColor = e.NewColor;
Color oldColor = e.OldColor;
Color newFillColor = e.NewFillColor;
int pageNumber = e.PageNumber;
}---
Ink Annotations
Enable / Disable
pdfViewer.InkAnnotationCommand.Execute(true); // Enable
pdfViewer.InkAnnotationCommand.Execute(false); // DisableCustomize Default Appearance
pdfViewer.InkAnnotationSettings.Color = Color.FromArgb(255, 255, 0, 0);
pdfViewer.InkAnnotationSettings.Opacity = 0.5f;
pdfViewer.InkAnnotationSettings.Thickness = 5;Improve Ink Smoothness
Use InkCanvas for smoother strokes (note: other annotations cannot be selected in this mode):
pdfViewer.InkAnnotationSettings.UseWindowsInkCanvas = true;Detect Ink Property Changes
pdfViewer.InkEdited += (s, e) =>
{
double newThickness = e.NewThickness;
Color newColor = e.NewColor;
int pageNumber = e.PageNumber;
};---
Popup Annotations
Enable / Disable
pdfViewer.PopupAnnotationCommand.Execute(true);
pdfViewer.PopupAnnotationCommand.Execute(false);Customize Default Appearance
pdfViewer.PopupAnnotationSettings.Color = Color.FromArgb(255, 255, 0, 0);
pdfViewer.PopupAnnotationSettings.Opacity = 0.5f;
pdfViewer.PopupAnnotationSettings.ScaleX = 2;
pdfViewer.PopupAnnotationSettings.ScaleY = 2;
pdfViewer.PopupAnnotationSettings.Icon = PopupIcon.Comment;Detect Popup Added
pdfViewer.PopupAnnotationAdded += (s, e) =>
{
PointF location = e.Location;
int pageNumber = e.PageNumber;
};---
Free Text Annotations
Enable / Disable
pdfViewer.FreeTextAnnotationCommand.Execute(true);
pdfViewer.FreeTextAnnotationCommand.Execute(false);Customize Default Appearance
pdfViewer.FreeTextAnnotationSettings.TextColor = Color.FromArgb(255, 255, 0, 0);
pdfViewer.FreeTextAnnotationSettings.TextSize = 10;
pdfViewer.FreeTextAnnotationSettings.FillColor = Color.FromArgb(255, 255, 255, 0);
pdfViewer.FreeTextAnnotationSettings.StrokeColor = Color.FromArgb(255, 0, 0, 255);
pdfViewer.FreeTextAnnotationSettings.StrokeWidth = 2;Detect Free Text Changes
pdfViewer.FreeTextAnnotationEdited += (s, e) =>
{
string newText = e.NewText;
string oldText = e.OldText;
double newSize = e.NewTextSize;
Color newColor = e.NewColor;
};---
Free Text Callout Annotations
Enable / Disable
pdfViewer.FreeTextCalloutAnnotationCommand.Execute(true);
pdfViewer.FreeTextCalloutAnnotationCommand.Execute(false);Customize Default Appearance
pdfViewer.FreeTextCalloutAnnotationSettings.TextColor = Color.FromArgb(255, 255, 0, 0);
pdfViewer.FreeTextCalloutAnnotationSettings.TextSize = 10;
pdfViewer.FreeTextCalloutAnnotationSettings.FillColor = Color.FromArgb(255, 255, 255, 0);
pdfViewer.FreeTextCalloutAnnotationSettings.StrokeColor = Color.FromArgb(255, 0, 0, 255);
pdfViewer.FreeTextCalloutAnnotationSettings.StrokeWidth = 2;
pdfViewer.FreeTextCalloutAnnotationSettings.Opacity = 0.5f;
pdfViewer.FreeTextCalloutAnnotationSettings.MinWidth = 100;
pdfViewer.FreeTextCalloutAnnotationSettings.MinHeight = 100;
// Auto-resize text box
pdfViewer.FreeTextCalloutAnnotationSettings.AutoSizeFreeTextInputBox = true;
// Callout line segments (One or Two)
pdfViewer.FreeTextCalloutAnnotationSettings.CalloutLineSegmentCount =
CalloutLineSegmentCount.One;---
Custom Stamp Annotations
Add any UIElement (Image, Button, etc.) as a stamp. Save using SaveAsync — not Save.
private async void Button_Clicked(object sender, RoutedEventArgs e)
{
Image image = new Image();
Stream imageStream = typeof(MainPage).GetTypeInfo().Assembly
.GetManifestResourceStream("MyApp.Assets.seal.png");
StackPanel grid = new StackPanel { Height = 100, Width = 100 };
BitmapImage bitmap = new BitmapImage();
bitmap.DecodePixelHeight = 500;
bitmap.DecodePixelWidth = 500;
await bitmap.SetSourceAsync(imageStream.AsRandomAccessStream());
image.Source = bitmap;
grid.Children.Add(image);
// AddStamp(view, pageNumber, position)
pdfViewer.AddStamp(grid, 1, new Point(100, 100));
}| Method Overload | Description |
|---|---|
AddStamp(view, pageNumber) | Add to page, default position |
AddStamp(view, pageNumber, Point) | Add to page at a specific Point |
AddStamp(view, pageNumber, Rect) | Add to page with specific bounds |
---
Deleting Annotations
Remove a Selected Annotation
IAnnotation selectedAnnotation;
pdfViewer.AnnotationSelected += (s, e) =>
{
selectedAnnotation = e.Annotation;
};
// Then on delete button click:
pdfViewer.RemoveAnnotation(selectedAnnotation);Remove All Annotations
pdfViewer.ClearAllAnnotations();---
Undo / Redo Annotation Changes
// Disable undo (also disables redo)
pdfViewer.IsUndoEnabled = false;Bind to XAML buttons:
<Button Command="{Binding ElementName=pdfViewer, Path=UndoCommand, Mode=TwoWay}"/>
<Button Command="{Binding ElementName=pdfViewer, Path=RedoCommand, Mode=TwoWay}"/>---
Check If Document Is Edited
IsDocumentEdited is true when annotations or form fields have been modified since the last save. Resets to false after saving.
<syncfusion:SfPdfViewerControl x:Name="pdfViewer"
IsDocumentEdited="{Binding DocumentEdited}"/>Bookmarks & Hyperlinks in UWP PDF Viewer (SfPdfViewerControl)
Bookmark Navigation
Navigate programmatically to a bookmark destination using GoToBookmark:
// Create the PdfLoadedDocument
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
// Retrieve the bookmark collection
PdfBookmarkBase bookmarks = loadedDocument.Bookmarks;
// Navigate to the first bookmark
pdfViewer.GoToBookmark(bookmarks[0]);Build a Bookmark UI with SfTreeNavigator
Iterate over bookmarks recursively to build a navigation tree:
private void LoadNavigator(PdfLoadedDocument loadedDocument)
{
PdfBookmarkBase bookmarkBase = loadedDocument.Bookmarks;
treeNavigator.Items.Clear();
for (int i = 0; i < bookmarkBase.Count; i++)
{
PdfBookmark bookmark = bookmarkBase[i] as PdfLoadedBookmark;
SfTreeNavigatorItem item = AddChildBookmarks(bookmark);
item.ItemClicked += NavigatorItem_ItemClicked;
treeNavigator.Items.Add(item);
}
}
private SfTreeNavigatorItem AddChildBookmarks(PdfBookmark bookmark)
{
if (bookmark == null) return null;
SfTreeNavigatorItem item = new SfTreeNavigatorItem
{
Header = bookmark.Title,
Padding = new Thickness(10),
Tag = bookmark
};
item.ItemClicked += NavigatorItem_ItemClicked;
for (int i = 0; i < bookmark.Count; i++)
{
SfTreeNavigatorItem child = AddChildBookmarks(bookmark[i]);
item.Items.Add(child);
}
return item;
}
private void NavigatorItem_ItemClicked(object sender,
Syncfusion.UI.Xaml.Controls.Navigation.ItemClickEventArgs args)
{
SfTreeNavigatorItem item = sender as SfTreeNavigatorItem;
PdfBookmark bookmark = item.Tag as PdfBookmark;
pdfViewer.GoToBookmark(bookmark);
}---
Hyperlink Navigation
By default, tapping a hyperlink in the PDF:
- Web link → opens URL in the default browser
- Document link → navigates to the destination page within the PDF
🔒 Security Best Practice: Validate Hyperlinks from Untrusted PDFs
⚠️ CRITICAL: When loading PDFs from untrusted or user-provided sources, never automatically open hyperlinks without validation. Malicious PDFs can contain hyperlinks designed to:
- Redirect users to phishing sites
- Trigger unintended navigation or actions
- Inject malicious content
Always implement hyperlink validation by handling the HyperlinkPointerPressed event to inspect and whitelist URLs before opening them.
Disable Hyperlink Navigation
If you don't need hyperlink support, disable it entirely:
pdfViewer.AllowHyperlinkNavigation = false;<syncfusion:SfPdfViewerControl x:Name="pdfViewerControl"
AllowHyperlinkNavigation="False"/>Handle Hyperlink Click (HyperlinkPointerPressed) - Validate Trusted Links
The SfPdfViewerControl exposes the `HyperlinkPointerPressed` event API to inspect hyperlinks before navigation. The event argument (HyperlinkEventArgs) provides the following parameters:
- `URI` - The hyperlink URL or internal PDF destination
- `PageIndex` - The page number where the hyperlink is located
- `DestinationPageIndex` - The target page (for document links)
- `Bounds` - The bounding rectangle of the hyperlink
- `HyperlinkType` - Indicates whether it is a
WebLinkorDocumentLink
Secure Pattern: Validate Web Links Before Opening
private HashSet<string> TrustedDomains = new HashSet<string>
{
"example.com",
"trusted-partner.com"
};
public MyPdfViewer()
{
pdfViewer.HyperlinkPointerPressed += OnHyperlinkPressed;
}
private async void OnHyperlinkPressed(object sender, HyperlinkEventArgs args)
{
// For document links, allow navigation within the same PDF
if (args.HyperlinkType == HyperlinkType.DocumentLink)
{
return; // Default behavior is safe
}
// For web links, validate the URL before opening
if (args.HyperlinkType == HyperlinkType.WebLink)
{
if (IsUrlTrusted(args.URI))
{
// Safely open the URL using platform API
await Windows.System.Launcher.LaunchUriAsync(new Uri(args.URI));
}
else
{
// Show user warning or block navigation
var dialog = new ContentDialog
{
Title = "Untrusted Link",
Content = $"This PDF contains a link to: {args.URI}\n\nDo you want to proceed?",
PrimaryButtonText = "Allow",
SecondaryButtonText = "Block"
};
var result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
await Windows.System.Launcher.LaunchUriAsync(new Uri(args.URI));
}
}
}
}
private bool IsUrlTrusted(string url)
{
try
{
var uri = new Uri(url);
var host = uri.Host.ToLower();
// Check against trusted domains
return TrustedDomains.Any(domain => host == domain || host.EndsWith("." + domain));
}
catch
{
return false; // Invalid URL is not trusted
}
}For programmatic URL navigation, always use the platform navigation API (Windows.System.Launcher.LaunchUriAsync) rather than handling raw PDF content directly.
Detect Mouse Hover Over Hyperlink (HyperlinkPointerMoved)
The viewer exposes the `HyperlinkPointerMoved` event API to detect when the pointer moves over a hyperlink. The event argument (HyperlinkEventArgs) provides:
- `URI` - The hyperlink URL or internal PDF destination
- `PageIndex` - The page number where the hyperlink is located
- `HyperlinkType` - Indicates whether it is a
WebLinkorDocumentLink
Use this event in combination with platform navigation APIs to open external URLs when required.
Restrict Navigation Selectively
To selectively control navigation, handle the viewer's `HyperlinkPointerPressed` event and call platform navigation APIs as needed; detailed code examples have been removed from this reference to avoid showing runtime handling of third-party content.
Getting Started with UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
- Required Assemblies
- Add SfPdfViewerControl via XAML
- Load PDF via Data Binding (ItemsSource)
- Load PDF via FileOpenPicker
- DocumentLoaded Event
- Saving a PDF Document
- Unloading and Disposing
---
Required Assemblies
Add the following assemblies as references to your UWP project:
Syncfusion.SfPdfViewer.UWPSyncfusion.Pdf.UWPSyncfusion.SfColorPickers.UWPSyncfusion.SfInput.UWPSyncfusion.SfRadialMenu.UWPSyncfusion.SfShared.UWP
Starting with v16.2.0.x, you must include a license key in your project when referencing Syncfusion assemblies from trial setup or NuGet.
---
Add SfPdfViewerControl via XAML
Add the Syncfusion.Windows.PdfViewer namespace and declare the control:
<Page
x:Class="SimpleSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:syncfusion="using:Syncfusion.Windows.PdfViewer">
<Grid>
<syncfusion:SfPdfViewerControl Name="pdfViewer"/>
</Grid>
</Page>Set the DataContext to the pdfViewer for command bindings in the toolbar:
this.DataContext = pdfViewer;---
Load PDF via Data Binding (ItemsSource)
ItemsSource accepts a Stream bound during initialization. Create a ViewModel class that loads the stream:
class PdfReport : INotifyPropertyChanged
{
private Stream docStream;
public event PropertyChangedEventHandler PropertyChanged;
public Stream DocumentStream
{
get { return docStream; }
set
{
docStream = value;
OnPropertyChanged(new PropertyChangedEventArgs("DocumentStream"));
}
}
public PdfReport()
{
// Load from embedded resource
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
docStream = assembly.GetManifestResourceStream("SimpleSample.Assets.sample.pdf");
}
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(this, e);
}
}Bind in XAML:
<Page Loaded="Page_Loaded">
<Page.DataContext>
<local:PdfReport/>
</Page.DataContext>
<Grid>
<syncfusion:SfPdfViewerControl Name="pdfViewer"
ItemsSource="{Binding DocumentStream}"/>
</Grid>
</Page>---
Load PDF via FileOpenPicker
The SfPdfViewerControl supports loading documents from an embedded resource, a Stream, a PdfLoadedDocument, or a StorageFile. To load a document at runtime, call the appropriate viewer API such as LoadDocument(Stream), LoadDocument(PdfLoadedDocument), or LoadDocument(StorageFile). You can monitor load completion using the `DocumentLoaded` event API.
🔒 Security Note: When loading PDFs from user-selected files or untrusted sources, ensure you:
- Validate file sources and only allow PDFs from trusted locations
- Implement hyperlink validation before allowing navigation (see Bookmarks & Hyperlinks)
- Disable hyperlink navigation (
AllowHyperlinkNavigation = false) if the feature is not required
---
Load PDF from Embedded Resource (Code-Behind)
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream fileStream = assembly.GetManifestResourceStream("MyApp.Assets.sample.pdf");
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(buffer);
pdfViewer.LoadDocument(loadedDocument);For async loading with cancellation support:
CancellationTokenSource cts = new CancellationTokenSource();
await pdfViewer.LoadDocumentAsync(loadedDocument, cts.Token);---
DocumentLoaded Event
Use DocumentLoaded to run logic after the PDF is fully rendered:
SfPdfViewerControl pdfViewer = new SfPdfViewerControl();
pdfViewer.DocumentLoaded += PdfViewer_DocumentLoaded;
private void PdfViewer_DocumentLoaded(object sender, DocumentLoadedEventArgs args)
{
// Get total page count after load
int pageCount = pdfViewer.PageCount;
}---
Saving a PDF Document
Save the document with annotations as a stream:
// Synchronous save (does not include stamp annotations)
Stream pdfDocumentStream = pdfViewer.Save();
// Asynchronous save (includes stamp annotations)
Task<Stream> pdfDocumentStream = pdfViewer.SaveAsync();To save to a file using FileSavePicker:
Stream stream = pdfViewer.Save();
stream.Position = 0;
FileSavePicker savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".pdf";
savePicker.SuggestedFileName = "output.pdf";
savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
StorageFile stFile = await savePicker.PickSaveFileAsync();
if (stFile != null)
{
var fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);
Stream st = fileStream.AsStreamForWrite();
st.SetLength(0);
st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
st.Flush();
st.Dispose();
fileStream.Dispose();
}---
Unloading and Disposing
Unload the PDF and release associated resources when the viewer is no longer needed:
// Unload the current PDF document
pdfViewer.Unload();
// Dispose all managed resources
pdfViewer.Dispose();---
Localization in UWP PDF Viewer (SfPdfViewerControl)
Localization lets you translate the PDF Viewer's context menu and UI strings to any language by providing .resw resource files.
---
Step 1: Set Default Language in App Manifest
1. Open Package.appxmanifest in the manifest designer. 2. On the Application tab, set the Default language (e.g., en-US, fr-FR). 3. Save the manifest.
---
Step 2: Add Resource Files
Create this folder structure in your project:
Resources/
├── en-US/
│ ├── Syncfusion.SfPdfViewerControl.UWP.Resources.resw
│ ├── Syncfusion.SfColorPickers.WinRT.Resources.resw
│ └── Localization.Resources.resw
└── fr-FR/
├── Syncfusion.SfPdfViewerControl.UWP.Resources.resw
├── Syncfusion.SfColorPickers.WinRT.Resources.resw
└── Localization.Resources.resw- Add the resource key names and their translated string values in the Resource Designer for each
.reswfile. - The
en-USfiles serve as the fallback/default.
---
Supported Resource File Names
| File | Purpose |
|---|---|
Syncfusion.SfPdfViewerControl.UWP.Resources.resw | PDF Viewer context menu and UI strings |
Syncfusion.SfColorPickers.WinRT.Resources.resw | Color picker strings |
Localization.Resources.resw | App-level localization strings |
---
Resource Keys and Translated Values
The following table lists the supported resource key names and their French (fr-FR) translated values for Syncfusion.SfPdfViewerControl.UWP.Resources.resw:
| Name | Value (fr-FR) |
|---|---|
| Color | Couleur |
| Delete | effacer |
| Edit | Éditer |
| FillColor | Remplir Couleur |
| Opacity | opacité |
| Open Pop-Up Note | ouvrir la note contextuelle |
| Properties | Propriétés |
| Text Size | taille du texte |
| Thickness | épaisseur |
| Type your text | Tapez votre texte |
These keys must be added to the.reswresource file under the matching locale folder (e.g.,Resources/fr-FR/Syncfusion.SfPdfViewerControl.UWP.Resources.resw).
---
Result
After adding the resource files with the correct keys and translations, the PDF Viewer's context menus and UI elements will display in the configured language automatically at runtime.
Magnification in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
- Zoom Commands
- Set Custom Zoom Percentage
- Get Current Zoom Value
- View Modes
- Minimum Zoom Percentage
- Disable Thumbnail View
---
Zoom Commands
Bind zoom commands to buttons when DataContext is pdfViewer:
<Button Content="Zoom In" Command="{Binding ElementName=pdfViewer, Path=IncreaseZoomCommand}"/>
<Button Content="Zoom Out" Command="{Binding ElementName=pdfViewer, Path=DecreaseZoomCommand}"/>---
Set Custom Zoom Percentage
Set a specific zoom level between 100 and 300:
// Zoom to 140%
pdfViewer.ZoomTo(140);---
Get Current Zoom Value
int currentZoom = pdfViewer.Zoom;---
View Modes
Three view modes are available via PageViewMode:
| Mode | Description |
|---|---|
PageViewMode.FitWidth | Fits the page width to the viewer |
PageViewMode.Normal | Default multi-page scrolling view |
PageViewMode.OnePage | Single page view (flip mode, mobile only) |
// Set to Fit Width
pdfViewer.ViewMode = PageViewMode.FitWidth;
// Set to Normal
pdfViewer.ViewMode = PageViewMode.Normal;
// Set to Single Page (mobile only)
pdfViewer.ViewMode = PageViewMode.OnePage;From XAML buttons in a custom toolbar:
private void FitWidthButtonClicked(object sender, RoutedEventArgs e)
{
pdfViewer.ViewMode = PageViewMode.FitWidth;
}
private void OnePageButtonClicked(object sender, RoutedEventArgs e)
{
pdfViewer.ViewMode = PageViewMode.OnePage;
}In Desktop view, when zoom drops below 100%, the view automatically switches to thumbnail mode.
One page view is supported only in mobile view (flip view).
---
Minimum Zoom Percentage
Set the minimum zoom level (accepted range: 10–100%):
pdfViewer.MinimumZoomPercentage = 30;Values below 10% are treated as 10%, values above 100% are treated as 100%. Default is the fit-page zoom computed at runtime.
---
Disable Thumbnail View
Prevent the automatic thumbnail view when zoom drops below 100%:
pdfViewer.IsThumbnailViewEnabled = false;Page Navigation in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
- Navigate Programmatically with GotoPage
- Navigation Commands
- Tracking Page Changes
- Page Count
- Page Gap Between Pages
- Page Offset Collection
- Scroll Offsets
- Toggle Page Number Display
---
Navigate Programmatically with GotoPage
// Navigate to page 5
pdfViewer.GotoPage(5);---
Navigation Commands
Bind these commands to XAML buttons when the page's DataContext is set to pdfViewer:
| Command | Action |
|---|---|
FirstPageCommand | Navigate to first page |
LastPageCommand | Navigate to last page |
PreviousPageCommand | Navigate to previous page |
NextPageCommand | Navigate to next page |
GoToPageCommand | Navigate to a specified page |
XAML Button Bindings
<Button Content="First" Command="{Binding FirstPageCommand}"/>
<Button Content="Last" Command="{Binding LastPageCommand}"/>
<Button Content="Previous" Command="{Binding PreviousPageCommand}"/>
<Button Content="Next" Command="{Binding NextPageCommand}"/>GoToPageCommand with TextBox Input
<!-- PageNumberTextBox provides the page number input -->
<TextBox x:Name="PageNumberTextBox"/>
<Button Content="Go"
Command="{Binding GoToPageCommand}"
CommandParameter="{Binding Path=Text, ElementName=PageNumberTextBox}"/>Navigate from Code with KeyDown
private void PageDestinationTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (!string.IsNullOrEmpty(PageDestinationTextBox.Text))
{
bool result = int.TryParse(PageDestinationTextBox.Text, out int destinationPage);
if (e.Key == VirtualKey.Enter && result)
{
if (destinationPage > 0 && destinationPage <= pdfViewer.PageCount)
{
pdfViewer.GotoPage(destinationPage);
e.Handled = true;
}
}
}
}---
Tracking Page Changes
The PageChanged event fires whenever the displayed page changes:
pdfViewer.PageChanged += PdfViewer_PageChanged;
private void PdfViewer_PageChanged(object sender, PageChangedEventArgs e)
{
// Update the current page indicator
pageNumberTextBlock.Text = e.NewPageNumber.ToString();
}---
Page Count
// Access total pages after DocumentLoaded fires
int pageCount = pdfViewer.PageCount;
PageCountText.Text = string.Format("of {0}", pageCount);---
Page Gap Between Pages
The gap in pixels between two adjacent pages being displayed:
int pageGap = pdfViewer.PageGap;---
Page Offset Collection
A dictionary with page numbers as keys and the vertical position where each page ends as values. Available only after the document is displayed:
Dictionary<int, double> offsetCollection = pdfViewer.PageOffsetCollection;The collection count will be 0 if accessed before the PDF is fully displayed.
---
Scroll Offsets
Get the current vertical and horizontal scroll position:
float verticalOffset = pdfViewer.VerticalOffset;
float horizontalOffset = pdfViewer.HorizontalOffset;---
Toggle Page Number Display
Show or hide the page number label on the top-left corner of each page:
pdfViewer.ShowPageNumber = false; // Hide
pdfViewer.ShowPageNumber = true; // Show (default)Printing PDF in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
- Print Using Method
- Print Using Command (XAML)
- Print Asynchronously
- Set Print Quality Factor
- Set Document Name for Print
- Customize Print Preview Options
- Disable Print Preview
---
Print Using Method
private void Button_Click(object sender, RoutedEventArgs e)
{
pdfViewer.Print();
}SfPdfViewerControl for UWP does not support silent printing. The document must be displayed in the viewer before printing.---
Print Using Command (XAML)
Bind PrintCommand to a button when DataContext is set to pdfViewer:
<syncfusion:SfPdfViewerControl Name="pdfViewer"/>
<Button Content="Print" Command="{Binding PrintCommand}"/>---
Print Asynchronously
For non-blocking print operations with cancellation support:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private async void printButton_Clicked(object sender, EventArgs e)
{
try
{
pdfViewer.PrinterSettings.DocumentName = "MyDocument.pdf";
await pdfViewer.PrintAsync(cancellationTokenSource);
}
catch (Exception ex)
{
ContentDialog printErrorDialog = new ContentDialog()
{
Title = "Printing error",
Content = "Printing cannot proceed at this time.",
PrimaryButtonText = "OK"
};
await printErrorDialog.ShowAsync();
}
}
// Cancel print in progress
private void cancelButton_Clicked(object sender, EventArgs e)
{
cancellationTokenSource.Cancel();
}Calling Cancel after printing completes has no effect.
---
Set Print Quality Factor
Control rendering quality for the print output. Range: 1–5 (1 = lowest, 5 = highest):
pdfViewer.PrinterSettings.QualityFactor = 2;Quality factors above 2 may cause OutOfMemoryException in x86 configurations.---
Set Document Name for Print
pdfViewer.PrinterSettings.DocumentName = "Invoice_2026.pdf";---
Customize Print Preview Options
Use PrintTaskRequested to add or modify options shown in the Windows print preview:
pdfViewer.PrintTaskRequested += PdfViewer_PrintTaskRequested;
private void PdfViewer_PrintTaskRequested(object sender,
SfPdfViewerPrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("Printing", sourceRequested =>
{
PrintTaskOptionDetails printDetailedOptions =
PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options);
IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
// Add page range options
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.CustomPageRanges);
printTask.Options.PageRangeOptions.AllowCurrentPage = true;
printTask.Options.PageRangeOptions.AllowAllPages = true;
printTask.Options.PageRangeOptions.AllowCustomSetOfPages = true;
sourceRequested.SetSource(e.PrintDocumentSource);
e.PrintTask = printTask;
});
}Only options supported by the selected printer appear in the print preview UI.
---
Disable Print Preview
pdfViewer.PrintTaskRequested += PrintTaskRequested;
private void PrintTaskRequested(object sender,
SfPdfViewerPrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("Printing", sourceRequested =>
{
sourceRequested.SetSource(e.PrintDocumentSource);
});
printTask.IsPreviewEnabled = false;
e.PrintTask = printTask;
}Text Operations in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
---
Text Selection
Enable / Disable Text Selection
Text selection is enabled by default. Disable it via property or XAML:
// Disable text selection
pdfViewerControl.IsTextSelectionEnabled = false;<syncfusion:SfPdfViewerControl x:Name="pdfViewerControl"
IsTextSelectionEnabled="False"/>Customize Selection Color
pdfViewerControl.TextSelectionSettings.SelectionColor =
Windows.UI.Color.FromArgb(150, 150, 207, 226);Show / Hide Copy Button
// Hide the copy button in the selection menu
pdfViewerControl.TextSelectionMenu.CopyButton.Visibility = Visibility.Collapsed;Get Selected Text
pdfViewer.TextSelectionCompleted += PdfViewer_TextSelectionCompleted;
private void PdfViewer_TextSelectionCompleted(object sender,
TextSelectionCompletedEventArgs e)
{
string selectedText = e.SelectedText;
}Text Search
Search Using Methods
// Search and highlight all matches on the current page
pdfViewer.SearchText("keyword");
// Navigate to next match
pdfViewer.SearchNextText("keyword");
// Navigate to previous match
pdfViewer.SearchPrevText("keyword");Search Using Commands (XAML)
<TextBox x:Name="PageSearchTxtBox"/>
<Button Content="Search Next"
Command="{Binding ElementName=pdfViewer, Path=SearchNextCommand}"
CommandParameter="{Binding Text, ElementName=PageSearchTxtBox}"/>
<Button Content="Search Previous"
Command="{Binding ElementName=pdfViewer, Path=SearchPreviousCommand}"
CommandParameter="{Binding Text, ElementName=PageSearchTxtBox}"/>Asynchronous Text Search
Useful for large documents — supports cancellation:
CancellationTokenSource cts = new CancellationTokenSource();
// Start async search
pdfViewer.SearchTextAsync("keyword", cts.Token);
// Search next instance async
pdfViewer.SearchNextTextAsync("keyword", cts.Token);
// Search previous instance async
pdfViewer.SearchPreviousTextAsync("keyword", cts.Token);
// Cancel in-progress search
cts.Cancel();Text search operations can only be performed after the PDF is displayed, not immediately after LoadDocument.Clear Search Highlights
pdfViewer.ClearTextSelectionCommand.Execute(true);---
Get Text Coordinates
Retrieve the screen coordinates of all instances of a text string on a specific page. Only works after the PDF is displayed.
private void Button_Click(object sender, RoutedEventArgs e)
{
List<PdfTextCoordinates> coordinates = new List<PdfTextCoordinates>();
pdfViewer.GetTextCoordinates("example", 4, out coordinates);
// coordinates contains position info for each match on page 4
}Returns a list of count 0 if called before the PDF is displayed.
Utilities & Advanced Features in UWP PDF Viewer (SfPdfViewerControl)
Table of Contents
---
Export Pages as Images
Export a Single Page as Image
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(buffer);
pdfViewer.LoadDocument(loadedDocument);
// Get page 2 as Image
Image pageImg = pdfViewer.GetPage(2);
// Get page 2 as Image at 300% zoom
Image pageImg = pdfViewer.GetPage(2, 300);Export Multiple Pages as Images
// Export pages 0 through 5 as Image array
Image[] pageImgCollection = pdfViewer.GetPages(0, 5);
// Export with custom zoom factor
Image[] pageImgCollection = pdfViewer.GetPages(0, 5, 200);Export as Image Stream (for saving to disk)
// Single page as Stream
Stream imageStream = pdfViewer.ExportAsImage(2);
// Single page at custom zoom
Stream imageStream = pdfViewer.ExportAsImage(2, 300);
// Multiple pages as List<Stream>
List<Stream> streamList = pdfViewer.ExportAsImage(0, 5);
// Multiple pages with zoom
List<Stream> streamList = pdfViewer.ExportAsImage(0, 5, 200);---
PDFium Custom Renderer
By default, SfPdfViewerControl uses the Windows rendering engine. To use the PDFium engine instead, implement the IPdfRenderer interface and assign it to the Renderer property.
Step 1 — Load the PDFium DLL
Load from a file path:
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(
[MarshalAs(UnmanagedType.LPTStr)] string lpFileName);
string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "pdfium.dll");
LoadLibrary(path);Or add pdfium.dll as a Content file in the project (no code loading needed).
Step 2 — Implement IPdfRenderer
Create a class with required external method definitions and interface methods:
// External PDFium method declarations
[DllImport("pdfium.dll", EntryPoint = "FPDF_InitLibrary")]
public static extern void FPDF_InitLibrary();
[DllImport("pdfium.dll")]
public static extern int FPDF_GetPageCount(IntPtr document);
// ... (other DllImport declarations for page size, bitmap, render, etc.)
public void Initialize(Stream stream, string password)
{
fileStream = stream;
FPDF_InitLibrary();
FPDF_FILEACCESS access = new FPDF_FILEACCESS
{
m_FileLen = (uint)fileStream.Length,
m_GetBlock = Marshal.GetFunctionPointerForDelegate(_getBlockDelegate),
m_Param = (IntPtr)2,
};
document = FPDF_LoadCustomDocument(access, password);
}
public int PageCount
{
get
{
if (pageCount == -1)
pageCount = FPDF_GetPageCount(document);
return pageCount;
}
}
public Size GetPageSize(int pageIndex)
{
double height = 0, width = 0;
FPDF_GetPageSizeByIndex(document, pageIndex, out width, out height);
return new Size { Width = (int)width, Height = (int)height };
}
public SoftwareBitmap RenderPageBitmap(int pageIndex, double pageWidth, double pageHeight)
{
var page = FPDF_LoadPage(document, pageIndex);
int width = (int)pageWidth;
int height = (int)pageHeight;
byte[] buffer = new byte[width * height * 4];
unsafe
{
fixed (byte* p = buffer)
{
IntPtr bitmap = FPDFBitmap_CreateEx(width, height, 4, (IntPtr)p, width * 4);
FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, FPDF.ANNOT);
FPDFBitmap_Destroy(bitmap);
FPDF_ClosePage(page);
}
}
SoftwareBitmap softwareBitmap = new SoftwareBitmap(
BitmapPixelFormat.Bgra8, width, height, BitmapAlphaMode.Premultiplied);
softwareBitmap.CopyFromBuffer(buffer.AsBuffer());
return softwareBitmap;
}
public void Close()
{
if (document != IntPtr.Zero)
FPDF_CloseDocument(document);
pageCount = -1;
}Step 3 — Assign the Renderer
sfPdfViewerControl.Renderer = new CustomerPDFRenderer();IfRendereris not set, the default Windows rendering engine is used. Ensure the correct architecture (x86 or x64) version ofpdfium.dllis used.
Viewing PDF in UWP PDF Viewer (SfPdfViewerControl)
The SfPdfViewerControl supports loading PDF documents from three source types — each available in both synchronous and asynchronous variants.
🔒 Security Considerations
When loading PDFs from untrusted sources (user-selected files, network, etc.):
- PDFs can contain malicious content including crafted hyperlinks and embedded scripts
- Always validate hyperlinks before allowing navigation (see Bookmarks & Hyperlinks - Security Best Practice)
- Consider disabling hyperlink navigation if not needed:
pdfViewer.AllowHyperlinkNavigation = false - Load PDFs from trusted sources when possible (embedded resources, verified downloads)
---
Loading from a PdfLoadedDocument Object
Synchronous
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream fileStream = assembly.GetManifestResourceStream("MyApp.Assets.sample.pdf");
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(buffer);
pdfViewer.LoadDocument(loadedDocument);Asynchronous (with cancellation)
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(buffer);
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
await pdfViewer.LoadDocumentAsync(loadedDocument, cancellationTokenSource.Token);---
Loading from a Stream Object
Synchronous
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream fileStream = assembly.GetManifestResourceStream("MyApp.Assets.sample.pdf");
pdfViewer.LoadDocument(fileStream);Asynchronous (with cancellation)
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream fileStream = assembly.GetManifestResourceStream("MyApp.Assets.sample.pdf");
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
await pdfViewer.LoadDocumentAsync(fileStream, cancellationTokenSource.Token);---
Loading from a StorageFile Object
The viewer supports loading a StorageFile (for example, when a file is provided by the app). Use LoadDocument(StorageFile) or LoadDocumentAsync(StorageFile, CancellationToken) to load such files. Monitor load completion with the `DocumentLoaded` event API; concrete file-picking examples are omitted here.
---
Cancelling Async Loading
Pass a CancellationToken to any LoadDocumentAsync call. To cancel while in progress:
CancellationTokenSource cts = new CancellationTokenSource();
// Start loading
await pdfViewer.LoadDocumentAsync(loadedDocument, cts.Token);
// To cancel:
cts.Cancel();---
Choosing the Right Load Method
| Scenario | Recommended Method |
|---|---|
| Embedded resource in app package | LoadDocument(PdfLoadedDocument) |
| File picked by user at runtime | LoadDocument(StorageFile) |
| Stream from network or memory | LoadDocument(Stream) |
| Large file needing cancellation | LoadDocumentAsync(...) with CancellationToken |
| XAML binding on startup | ItemsSource="{Binding DocumentStream}" |