技术开发 频道

简单实用 利用WPF 浏览PDF 文件

  打开控件程序,修改构造函数。将PDF 文件传入控件并进行加载。

using System.Windows.Forms;

namespace WpfPDFReader
{
    
public partial class AdobeReaderControl : UserControl
    {
        
public AdobeReaderControl(string fileName)
        {
            InitializeComponent();

            this.axAcroPDF1.LoadFile(fileName);
        }
    }
}

 

  到此用户控件就基本完成了,下面开始WPF 部分的开发。

  WPF

  由于要将上面的WinForm 控件加载到WPF 程序中,所以先要为WPF 添加WindowsFormsIntegration。

1
 

  打开XAML 在<Grid> 中添加Button 和WindowsFormsHost 控件,其中Button 用来启动文件目录窗口,从中选择要浏览的PDF文件;WindowsFormsHost 则用于嵌入WinForm 控件。

<Window x:Class="WpfPDFReader.MainWindow"
        xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
        Title
="WPF PDF Reader" Height="350" Width="525">
    
<Grid>
        
<Button Content="Open File" Click="Button_Click" Width="100" Height="30"
                VerticalContentAlignment
="Center" VerticalAlignment="Top"
                Margin
="0,10,0,0"/>
        
<WindowsFormsHost x:Name="winFormHost" Margin="0,46,0,0" />
    
</Grid>
</Window>



  下面来完成Button 点击事件,将通过OpenFileDialog 选择的PDF 文件路径及名称传入AdobeReaderControl 用户控件中,并将该控件添加到WindowsFormsHost。

private string openFileName;
private OpenFileDialog openFileDialog;

private void Button_Click(object sender, RoutedEventArgs e)
{
    openFileDialog
= new OpenFileDialog();
    openFileDialog.DefaultExt
= "pdf";
    openFileDialog.Filter
= "pdf files (*.pdf)|*.pdf";

    DialogResult result
= openFileDialog.ShowDialog();

    
if (result == System.Windows.Forms.DialogResult.OK)
    {
        openFileName
= openFileDialog.FileName;

        AdobeReaderControl pdfCtl
= new AdobeReaderControl(openFileName);
        winFormHost.Child
= pdfCtl;                
    }
    
else
    {
        return;
    }
}

 

  F5看下效果,点击“Open File” 选择一个PDF ,这样一个简单的WPF PDF Reader 就完成了。

1
 

0
相关文章