View PDF files within WinForms applications

This blog discusses method to view pdf files in Winform application that can be done by porting currently available WPF C1PDFViewer into Winform. C1PDF is available to create and save pdf in Winform applications, but to complement it we can use WPF C1PDFViewer in Winform so that we can View pdf files also. For example, we can use C1PDF to create pdf and then use C1PDFViewer to view in within the Winform application. In, order to use WPF C1PDFViewer we need to create a new win form application and add WPF user control that contains the C1PDFViewer.Now we add the WPF User control to our Windows form using ElementHost.

Detailed Implementation

Step 1: Create a new Winform application and add WPF user control In this we simply create a new Winform application and then add WPF User Control.Also, we need to add a reference of “WindowsFormsIntegration” in our application. Step2 : Insert C1PDFViewer in User Control using the code below Here, we insert C1PDF viewer into our User control using the following code

   <Grid>  
    <Grid.RowDefinitions>  
       <RowDefinition Height="auto" />  
       <RowDefinition />  
    </Grid.RowDefinitions>  
    <Grid>  
       <Grid.ColumnDefinitions>  
          <ColumnDefinition />  
          <ColumnDefinition Width="auto"/>  
       </Grid.ColumnDefinitions>  
       <TextBlock Text="Select a PDF file, then print/preview/save it from the C1PdfViewer." VerticalAlignment="Center" Margin="6 0" />  
       <Button Content="Load PDF File..." HorizontalAlignment="Right" Padding="6 2" Grid.Column="1" Click="Button_Click"/>  
    </Grid>  

    <c1:C1PdfViewer x:Name="_c1pdf" Grid.Row="1" />  

 </Grid>

Now in code behind we load the pdf in button click event :

   private void Button_Click(object sender, RoutedEventArgs e)  
 {  
       var dlg = new Microsoft.Win32.OpenFileDialog();  
       dlg.Filter ="PDF files (*.pdf)|*.pdf";  
       if (dlg.ShowDialog().Value)  
          _c1pdf.LoadDocument(dlg.FileName);  
 }

Step3 : Insert WPF User Control in Windows Form WPF User Control can be inserted into Windows Form using ElementHost that is present in the Toolbox underneath “WPF Interoperability”. So once we drag an ElementHost onto your form, we need to click on the little arrow on the upper right of the ElementHost and open the combobox for “Select Hosted Content”. After , this we need to choose the WPF control we want to host in the ElementHost. Once this is done we can simply run the application and view pdf files in our Winform application. Please refer to attached sample ‘SamplePdfViewer’ shows the implementation of using WPF C1PDFViewer in Winforms. Download Sample

GrapeCity

GrapeCity Developer Tools
comments powered by Disqus