文章出處

 

添加成功后會在工具箱里看到下圖所示的控件。打開VS2010,新建項目(WpfPDFReader),右鍵項目添加User Control(用戶控件)。因為Adobe PDF Reader COM 組件是不支持WPF的,為此我們需要將它放到WinForm 控件中。所以,在列表中需要選擇User Control,而不是User Control(WPF)。這里我將控件命名為:AdobeReaderControl.cs。完成添加雙擊控件進入設計模式。

在工具箱里選擇添加組件,在COM 組件列表中點選“Adobe PDF Reader”。

 

AcroPDFLib 和AxAcroPDFLib 庫會自動添加到項目中。

添加成功后會在工具箱里看到下圖所示的控件。

將該COM 控件拖入User Control 。

 

控件默認名稱為:axAcroPDF1,可按需要自行更改。

 

Dock屬性設置為“Fill”,這樣可以使控件自動適應窗口尺寸。

打開控件程序,修改構造函數。將PDF 文件傳入控件并進行加載。

 
using System.Windows.Forms;

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

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

到此用戶控件就基本完成了,下面開始WPF 部分的開發。

由于要將上面的WinForm 控件加載到WPF 程序中,所以先要為WPF 添加WindowsFormsIntegration。

 

 

  打開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 就完成了。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()