How do I use PDFControls.NET in a WPF application

UI, WPF / XPS, View, Manipulate PDF


This code sample shows you how PDFControls.NET can be used in a WPF application.


WinForms controls can be used in a WPF application via the WindowsFormsHost class. In order to use this, you will first need to reference the WindowsFormsIntegration assembly in your WPF project. Then, you can use the WindowsFormsHost as an element in your GUI and map it to a WinForms control. The XAML code below shows you how to do this.

1 <Window x:Class="WpfApplication1.MainWindow" 2 xmlns="" 3 xmlns:x="" 4 xmlns:tc="clr-namespace:TallComponents.Interaction.WinForms.Controls; 5 assembly=TallComponents.PDF.Controls.WinForms" 6 Title="MainWindow" Height="350" Width="525"> 7 <Grid> 8 <Menu Height="26" Name="menu1" VerticalAlignment="Top"> 9 <MenuItem Header="File" Click="MenuItem_Click"> 10 <MenuItem Header="Open..." Click="MenuItem_Open"></MenuItem> 11 </MenuItem> 12 </Menu> 13 <WindowsFormsHost Name="windowsFormsHost1" 14 ChildChanged="windowsFormsHost1_ChildChanged" Margin="0,32,0,0"> 15 <tc:PagesViewer Name="_pagesViewer"/> 16 </WindowsFormsHost> 17 </Grid> 18 </Window>

Please note that the XAML code above defines a "tc" namespace that does 2 things: First of all, it specifies the name of the PDFControls.NET assembly (TallComponents.PDF.Controls.WinForms). Secondly, it defines a shortcut to a particular namespace withing this assembly, in this case TallComponents.Interaction.WinForms.Controls.

From that point on, the WindowsFormHost can refer to controls within this namespace using the "tc" namespace, in this case tc:PagesViewer.


The next step is to actually do something with the control. The code below shows a handler for the "Open" menu item. It pops up a file dialog for opening a file. Once it has obtained a file path it will look for the PagesViewer that is located in the WinForms Forms Host. From that point on, one just has to let the PagesViewer open the specified file.

1 private void MenuItem_Open(object sender, RoutedEventArgs e) 2 { 3 Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); 4 dialog.DefaultExt = ".pdf"; 5 dialog.Filter = "PDF documents (.pdf)|*.pdf"; // Filter files by extension 6 7 Nullable<bool> result = dialog.ShowDialog(); 8 9 if (result == true) 10 { 11 string path = dialog.FileName; 12 13 PagesViewer pagesViewer = windowsFormsHost1.Child as PagesViewer; 14 15 if (pagesViewer.Document == null) 16 { 17 pagesViewer.Document = new Document(); 18 } 19 pagesViewer.Document.Open(path); 20 } 21 }