WPF 瀏覽PDF 文件

作者: Gnie  來源: 博客園  發布時間: 2010-11-18 22:00  閱讀: 2755 次  推薦: 1   原文鏈接   [收藏]  

     很長時間沒寫文章感覺手有點生了,前段時間忙的要死公事、家事、私事,事事操心。還好現在有些時間可以繼續寫博客了。本篇將為大家演示如何在WPF 程序中瀏覽PDF 文件,本例將通過Adobe PDF Reader COM 組件、WinForm 與WPF 集成方面的工具實現PDF 瀏覽功能。

  用戶控件

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

AddUserCtl

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

SelectCom

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

Reference

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

Toolbox

  將該COM 控件拖入User Control 。

AddCom

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

ComName

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

Dock

  打開控件程序,修改構造函數。將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。

WinForm

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

Reader

  源代碼:WpfPDFReader.zip

1
0
 
標簽:WPF
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

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