|
很長時間沒寫文章感覺手有點(diǎn)生了,前段時間忙的要死公事、家事、私事,事事操心。還好現(xiàn)在有些時間可以繼續(xù)寫博客了。本篇將為大家演示如何在WPF 程序中瀏覽PDF 文件,本例將通過Adobe PDF Reader COM 組件、WinForm 與WPF 集成方面的工具實現(xiàn)PDF 瀏覽功能。
用戶控件
打開VS2010,新建項目(WpfPDFReader),右鍵項目添加User Control(用戶控件)。因為Adobe PDF Reader COM 組件是不支持WPF的,為此我們需要將它放到WinForm 控件中。所以,在列表中需要選擇User Control,而不是User Control(WPF)。這里我將控件命名為:AdobeReaderControl.cs。完成添加雙擊控件進(jìn)入設(shè)計模式。
在工具箱里選擇添加組件,在COM 組件列表中點(diǎn)選“Adobe PDF Reader”。
AcroPDFLib 和AxAcroPDFLib 庫會自動添加到項目中。
添加成功后會在工具箱里看到下圖所示的控件。
將該COM 控件拖入User Control 。
控件默認(rèn)名稱為:axAcroPDF1,可按需要自行更改。
Dock屬性設(shè)置為“Fill”,這樣可以使控件自動適應(yīng)窗口尺寸。
打開控件程序,修改構(gòu)造函數(shù)。將PDF 文件傳入控件并進(jìn)行加載。
using System.Windows.Forms;
namespace WpfPDFReader
{
public partial class AdobeReaderControl : UserControl
{
public AdobeReaderControl(string fileName)
{
InitializeComponent();
this.axAcroPDF1.LoadFile(fileName);
}
}
}
到此用戶控件就基本完成了,下面開始WPF 部分的開發(fā)。
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 點(diǎn)擊事件,將通過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看下效果,點(diǎn)擊“Open File” 選擇一個PDF ,這樣一個簡單的WPF PDF Reader 就完成了。
源代碼:WpfPDFReader.zip
NET技術(shù):WPF 瀏覽PDF 文件,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。