How do I use PDFControls.NET in a WPF application
How do I use PDFControls.NET in a WPF application
This code sample shows you how PDFControls.NET can be used in a WPF application.
XAML
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.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tc="clr-namespace:TallComponents.Interaction.WinForms.Controls;
assembly=TallComponents.PDF.Controls.WinForms"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Menu Height="26" Name="menu1" VerticalAlignment="Top">
<MenuItem Header="File" Click="MenuItem_Click">
<MenuItem Header="Open..." Click="MenuItem_Open"></MenuItem>
</MenuItem>
</Menu>
<WindowsFormsHost Name="windowsFormsHost1"
ChildChanged="windowsFormsHost1_ChildChanged" Margin="0,32,0,0">
<tc:PagesViewer Name="_pagesViewer"/>
</WindowsFormsHost>
</Grid>
</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 within 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.
C#
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.
private void MenuItem_Open(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
dialog.DefaultExt = ".pdf";
dialog.Filter = "PDF documents (.pdf)|*.pdf"; // Filter files by extension
Nullable<bool> result = dialog.ShowDialog();
if (result == true)
{
string path = dialog.FileName;
PagesViewer pagesViewer = windowsFormsHost1.Child as PagesViewer;
if (pagesViewer.Document == null)
{
pagesViewer.Document = new Document();
}
pagesViewer.Document.Open(path);
}
}