ImageGear .NET
Windows Presentation Foundation (WPF)

In this tutorial, you will configure a C# or VB.NET project for a Windows Presentation Foundation (WPF) application and use ImageGear .NET PDF capabilities. You will also learn how to open a PDF or PS file, display it on the screen, and navigate through the different pages of the PDF.

The following tutorial refers specifically to 64-bit installations; for 32-bit installations:

  • Your project should already be set to compile to target Debug and x86, and you should have the directory: $YOURLOCALPROJ\bin\x86\Debug\.
  • Throughout these instructions, replace x64 with x86.
  • The 32-bit ImageGear binaries are found in $INSTALLDIR\ImageGear .NET v23\Bin\

Using the desired version of Visual Studio (2010 or later):

  1. Create a new "WPF Application" project, using C# or VB.NET, and name the project: my_first_PDF_WPF_project
  2. If you installed ImageGear .NET 64-bit, using the Configuration Manager, create a new project platform (if you don’t have one already) for x64. Make sure your project is set to compile targeting Debug and x64. Make sure you now have $YOURLOCALPROJ\bin\x64\Debug\, and if is not there, create it.
  3. Add references and required resources into your projects in one of the following ways:
    • Recommended: use our NuGet Packages. For this project, you need the following packages:
    • Manually:
      • Copy all files (and folders) inside $INSTALLDIR\ImageGear .NET v23 64-bit\Bin\ to your local output bin directory in your project (i.e., $YOURLOCALPROJ\bin\x64\Debug\ ).
      • Add the following references to your project from $YOURLOCALPROJ\bin\x64\Debug\:
        • ImageGear23.Core.dll
        • ImageGear23.Evaluation.dll
        • ImageGear23.Formats.Common.dll
        • ImageGear23.Formats.Pdf.dll
        • ImageGear23.Formats.Vector.dll
        • ImageGear23.Presentation.dll
        • ImageGear23.Windows.Controls.dll
        • ImageGear23.Wpf.dll

    Your output target directory should be set to $YOURLOCALPROJ\bin\x64\Debug\

  4. Open the MainWindow.xaml screen with both the Design and XAML panels for the window visible. You will use the XAML panel to create the graphical user interface. First, in the XAML panel, create a custom alias namespace. So, add some code to the header so it looks like this:
    XAML
    Copy Code

    <Window x:Class="my_first_PDF_WPF_project.MainWindow"

           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:IGWC="clr-namespace:ImageGear.Windows.Controls;assembly=ImageGear23.Windows.Controls"

           Title="MainWindow" Height="714" Width="1035" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

    </Window>

  5. For organizational purposes we will use a Grid. Inside of that Grid, add a Menu. That Menu will have a File > Open … item that will be responsible for opening a PDF file. In the Grid, we will also add a StatusBar to offer feedback to the user. The XML code to add the mentioned controls is the following:
    XAML
    Copy Code

    <Window x:Class="my_first_PDF_WPF_project.MainWindow"

           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

           xmlns:IGWC="clr-namespace:ImageGear.Windows.Controls;assembly=ImageGear23.Windows.Controls"

           Title="MainWindow" Height="714" Width="1035" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

       <Grid>

           <Grid.ColumnDefinitions>

               <ColumnDefinition Width="91*" />

               <ColumnDefinition Width="4*" />

               <ColumnDefinition Width="44*" />

               <ColumnDefinition Width="888*" />

           </Grid.ColumnDefinitions>

           <Menu Height="20" HorizontalAlignment="Stretch" Name="menu" VerticalAlignment="Top" Grid.ColumnSpan="4">

                   <MenuItem Name="menuItemFileOpen" Header="Open PDF ..." Click="menuItemFileOpen_Click"/>

           </Menu>

           <StatusBar Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" VerticalContentAlignment="Center" HorizontalContentAlignment="Stretch" Margin="0,0,0,-1" Grid.ColumnSpan="4">

               <StatusBarItem Name="statusLabel" DataContext="{Binding}" BorderBrush="Black" BorderThickness="0" VerticalAlignment="Center" />

           </StatusBar>

       </Grid>

    </Window>

  6. To finish the GUI, we need to add a PageView control, which will be used to display the PDF document, and the ImGearThumbnailList that will be used to navigate through the document. The entire XAML file should now look like this:
    XAML
    Copy Code

    <Window x:Class="my_first_PDF_WPF_project.MainWindow"

           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

           xmlns:IGWC="clr-namespace:ImageGear.Windows.Controls;assembly=ImageGear23.Windows.Controls"

           Title="MainWindow" Height="714" Width="1035" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

       <Grid>

           <Grid.ColumnDefinitions>

               <ColumnDefinition Width="91*" />

               <ColumnDefinition Width="4*" />

               <ColumnDefinition Width="44*" />

               <ColumnDefinition Width="888*" />

           </Grid.ColumnDefinitions>

           <Menu Height="20" HorizontalAlignment="Stretch" Name="menu" VerticalAlignment="Top" Grid.ColumnSpan="4">

                   <MenuItem Name="menuItemFileOpen" Header="Open Document ..." Click="menuItemFileOpen_Click"/>

           </Menu>

           <StatusBar Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" VerticalContentAlignment="Center" HorizontalContentAlignment="Stretch" Margin="0,0,0,-1" Grid.ColumnSpan="4">

               <StatusBarItem Name="statusLabel" DataContext="{Binding}" BorderBrush="Black" BorderThickness="0" VerticalAlignment="Center" />

           </StatusBar>

           <IGWC:ImGearThumbnailList Name="igThumbnailList" Margin="12,26,0,30" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="90" ItemHeight="80" ItemWidth="60" SelectionChanged="igThumbnailList_SelectionChanged" Grid.ColumnSpan="3" />

           <IGWC:PageView Name="igPageView" Margin="20,26,12,30" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="LightGray" Grid.Column="2" Grid.ColumnSpan="2" />

       </Grid>

    </Window>

  7. Next, let's add the functionality to the controls in the  MainWindow.xaml.cs file.  First add some using statements and declare the some members required for this project in the .xaml.cs file. Open MainWindow.xaml.cs and add code similar to the following within the body of your MainWindow class:
    C#
    Copy Code
    using System;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    
    using ImageGear.Evaluation;
    using ImageGear.Core;
    using ImageGear.Formats;
    using ImageGear.Formats.PDF;
    
    namespace my_first_PDF_WPF_project
    {
       public partial class MainWindow : Window
       {
           // Current loaded PDF document.
           private ImGearPDFDocument igPdfDocument = null;
    
           // Directory for PDF file selection dialog.
           private string fileOpenDialogInitialDirectory;
       }
    }
    VB.NET
    Copy Code
    Imports System.IO
    Imports System.Windows
    Imports System.Windows.Controls
    
    Imports ImageGear.Evaluation
    Imports ImageGear.Core
    Imports ImageGear.Formats
    Imports ImageGear.Formats.PDF
    
    Namespace my_first_PDF_WPF_project
                Public Partial Class MainWindow
                            Inherits Window
                            ' Current loaded PDF document.
                            Private igPdfDocument As ImGearPDFDocument = Nothing
    
                            ' Directory for PDF file selection dialog.
                            Private fileOpenDialogInitialDirectory As String
                End Class
    End Namespace
  8. First, we need to initialize and support processing of PDF and PS files:
    C#
    Copy Code
    public MainWindow()
           {
               InitializeComponent();
    
               // Initialize evaluation manager.
               ImGearEvaluationManager.Initialize();
    
               // Use watermark mode for evaluation license.
               ImGearEvaluationManager.Mode = ImGearEvaluationMode.Watermark;
    
               // Initialize common formats.
               ImGearCommonFormats.Initialize();
    
               // Add PDF file format filter to filter list.
               ImGearFileFormats.Filters.Insert(0, ImGearPDF.CreatePDFFormat());
               ImGearFileFormats.Filters.Insert(0, ImGearPDF.CreatePSFormat());
    
               // Initialize PDF engine.
               ImGearPDF.Initialize();
    
               // Create page display one time.
               igPageView.Display = new ImageGear.Display.ImGearPresentationPageDisplay();
    
               // Prepare common images directory.
               string commonImagesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
               commonImagesDirectory = System.IO.Path.Combine(commonImagesDirectory, @"Accusoft\Common\Images");
               if (!Directory.Exists(commonImagesDirectory))
                   Directory.CreateDirectory(commonImagesDirectory);
    
               // Update initial directory for file dialogs with common images directory.
               fileOpenDialogInitialDirectory = commonImagesDirectory;
           }
    VB.NET
    Copy Code
    Public Sub New()
                InitializeComponent()
    
                ' Initialize evaluation manager.
                ImGearEvaluationManager.Initialize()
    
                ' Use watermark mode for evaluation license.
                ImGearEvaluationManager.Mode = ImGearEvaluationMode.Watermark
    
                ' Initialize common formats.
                ImGearCommonFormats.Initialize()
    
                ' Add PDF file format filter to filter list.
                ImGearFileFormats.Filters.Insert(0, ImGearPDF.CreatePDFFormat())
                ImGearFileFormats.Filters.Insert(0, ImGearPDF.CreatePSFormat())
    
                ' Initialize PDF engine.
                ImGearPDF.Initialize()
    
                ' Create page display one time.
                igPageView.Display = New ImageGear.Display.ImGearPresentationPageDisplay()
    
                ' Prepare common images directory.
                Dim commonImagesDirectory As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)
                commonImagesDirectory = System.IO.Path.Combine(commonImagesDirectory, "Accusoft\Common\Images")
                If Not Directory.Exists(commonImagesDirectory) Then
                            Directory.CreateDirectory(commonImagesDirectory)
                End If
    
                ' Update initial directory for file dialogs with common images directory.
                fileOpenDialogInitialDirectory = commonImagesDirectory
    End Sub
  9. Next, add the code for opening a PDF or PS file.
    C#
    Copy Code
    // Calls open file dialog for getting PDF file name and loads the document from this file.
           private void menuItemFileOpen_Click(object sender, RoutedEventArgs e)
           {
               try
               {
                   // Initialize open file dialog.
                   Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
                   dialog.Filter = ImGearFileFormats.GetSavingFilter(ImGearSavingFormats.PDF) + "|" +
                   ImGearFileFormats.GetSavingFilter(ImGearSavingFormats.PS);
                   dialog.Title = "Open PDF Document";
                   dialog.InitialDirectory = fileOpenDialogInitialDirectory;
    
                   // Run open file dialog.
                   if (dialog.ShowDialog(this) == true)
                   {
    
                       // Store initial directory for further dialog run.
                       fileOpenDialogInitialDirectory = System.IO.Path.GetDirectoryName(dialog.FileName);
    
                       // Load PDF document from a file.
                       ImGearDocument igDocument;
                       using (System.IO.Stream stream = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                           igDocument = ImGearFileFormats.LoadDocument(stream);
    
                       // Check the document is PDF document.
                       if (!(igDocument is ImGearPDFDocument))
                           throw new ApplicationException("Selected document is valid document but not a PDF document.");
    
                       // Clear previously loaded document.
                       if (igPdfDocument != null)
                       {
                           igPdfDocument.Dispose();
                           igPdfDocument = null;
                       }
    
                       // Store current loaded document.
                       igPdfDocument = (ImGearPDFDocument)igDocument;
    
                       // Refill thumbnail list with new page thumbnails.
                       igThumbnailList.Items.Clear();
                       foreach (ImGearPDFPage page in igPdfDocument.Pages)
                           igThumbnailList.Items.Add(new ImageGear.Windows.Controls.ImGearThumbnailPage(page));
    
                       // Set first thumbnail in list as a current.
                       igThumbnailList.SelectedIndex = 0;
    
                       // Output result to the status bar.
                       statusLabel.Content = "PDF document is successfully loaded from \"" + dialog.FileName + "\".";
                   }
               }
               catch (Exception exp)
               {
                   // Expose the error in status bar and message box.
                   statusLabel.Content = exp.Message;
                   MessageBox.Show(this, exp.Message);
               }
    
           }
    VB.NET
    Copy Code
    ' Calls open file dialog for getting PDF file name and loads the document from this file.
    Private Sub menuItemFileOpen_Click(sender As Object, e As RoutedEventArgs)
                Try
                            ' Initialize open file dialog.
                            Dim dialog As New Microsoft.Win32.OpenFileDialog()
                            dialog.Filter = ImGearFileFormats.GetSavingFilter(ImGearSavingFormats.PDF) + "|" + ImGearFileFormats.GetSavingFilter(ImGearSavingFormats.PS)
                            dialog.Title = "Open PDF Document"
                            dialog.InitialDirectory = fileOpenDialogInitialDirectory
    
                            ' Run open file dialog.
                            If dialog.ShowDialog(Me) = True Then
    
                                        ' Store initial directory for further dialog run.
                                        fileOpenDialogInitialDirectory = System.IO.Path.GetDirectoryName(dialog.FileName)
    
                                        ' Load PDF document from a file.
                                        Dim igDocument As ImGearDocument
                                        Using stream As System.IO.Stream = New System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
                                                    igDocument = ImGearFileFormats.LoadDocument(stream)
                                        End Using
    
                                        ' Check the document is PDF document.
                                        If Not (TypeOf igDocument Is ImGearPDFDocument) Then
                                                    Throw New ApplicationException("Selected document is valid document but not a PDF document.")
                                        End If
    
                                        ' Clear previously loaded document.
                                        If igPdfDocument IsNot Nothing Then
                                                    igPdfDocument.Dispose()
                                                    igPdfDocument = Nothing
                                        End If
    
                                        ' Store current loaded document.
                                        igPdfDocument = DirectCast(igDocument, ImGearPDFDocument)
    
                                        ' Refill thumbnail list with new page thumbnails.
                                        igThumbnailList.Items.Clear()
                                        For Each page As ImGearPDFPage In igPdfDocument.Pages
                                                    igThumbnailList.Items.Add(New ImageGear.Windows.Controls.ImGearThumbnailPage(page))
                                        Next
    
                                        ' Set first thumbnail in list as a current.
                                        igThumbnailList.SelectedIndex = 0
    
                                        ' Output result to the status bar.
                                        statusLabel.Content = "PDF document is successfully loaded from """ + dialog.FileName + """."
                            End If
                Catch exp As Exception
                            ' Expose the error in status bar and message box.
                            statusLabel.Content = exp.Message
                            MessageBox.Show(Me, exp.Message)
                End Try
    
    End Sub
  10. Also, the code to navigate across the pages in the PDF document using the Thumbnail list:
    C#
    Copy Code
    // Sets current selected in thumbnail list page to main page view.
           private void igThumbnailList_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
               if (igThumbnailList.SelectedIndex >= 0 && igPdfDocument != null)
               {
                   igPageView.Page = igPdfDocument.Pages[igThumbnailList.SelectedIndex];
                   igPageView.Update();
               }
           }
    VB.NET
    Copy Code
    ' Sets current selected in thumbnail list page to main page view.
    Private Sub igThumbnailList_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
                If igThumbnailList.SelectedIndex >= 0 AndAlso igPdfDocument IsNot Nothing Then
                            igPageView.Page = igPdfDocument.Pages(igThumbnailList.SelectedIndex)
                            igPageView.Update()
                End If
    End Sub
  11. And finally, the code to properly dispose of all the used controls:
    C#
    Copy Code
    // Properly dispose of PDF and other objects.
    protected override void OnClosed(EventArgs e)
    {
       ImGearPDF.Terminate();
       igPageView.Display = null;
       this.Close();
    }
    VB.NET
    Copy Code
    ' Properly dispose of PDF and other objects.
    Protected Overrides Sub OnFormClosed(ByVal e As FormClosedEventArgs)
                ImGearPDF.Terminate()
                igPageView.Display = Nothing
                Me.Close()
    End Sub

This sample project was created as a simple introduction to using the PDF functionality in ImageGear. For systems designed for production environments, you need to configure your projects more efficiently by only adding the resources that you need. For more information, refer to Deploying Your Product.

 

 


©2017. Accusoft Corporation. All Rights Reserved.

Send Feedback