【转】How to view word document in WPF application

How to view word document in WPF application (CSVSTOViewWordInWPF)

Introduction

The Sample demonstrates how to view word document in WPF application. WPF does not support to view Word documents directly but some customers want to show word document in WPF. So we can use WPF DocumentViewer control to host fixed document such as XPS document. And we also can convert word document to xps document using VSTO.

Building the Sample

Before building the sample, please make sure that you have Installed Microsoft Office 2010 on your machine.

Running the Sample

Step 1. Open CSVSTOViewWordInWPF.sln and click Ctrl+F5 to run the project. You will see the following form:

Step 2. Click "Select Word File" button to select an existing word document on your machine

Step 3. Click "View Word Doc" button to View Word document in WPF DocumentViewer control. If word document isn't exist, when you click the "View Word Doc", you will get the prompt message with "The file is invalid. Please select an existing file again."

If word document is existing on machine and there is no error occurs, you will see the following form:

Using the Code

Step 1. Create WPF Application project via Visual Studio

Step 2. Add needed references to the project

Step 3. Import the needed namespace into the mainWindow.xaml.cs class.

C#

using System;  using System.IO;  using System.Windows;  using System.Windows.Xps.Packaging;  using Microsoft.Office.Interop.Word;  using Microsoft.Win32;  using Word = Microsoft.Office.Interop.Word;   

Step 4. Design WPF UI form using XAML codes

XAML

<Grid>         <Grid.RowDefinitions>             <RowDefinition Height="70"></RowDefinition>             <RowDefinition></RowDefinition>         </Grid.RowDefinitions>         <Label Name="lable1" Margin="3,6,0,0" Content="Word Document :" VerticalAlignment="Top" HorizontalAlignment="Left" />         <TextBox  Name="txbSelectedWordFile" VerticalAlignment="Top"  HorizontalAlignment="Stretch" Margin="110,10,300,0" HorizontalContentAlignment="Left" />         <Button HorizontalAlignment="Right" VerticalAlignment="Top" Width="150" Content="Select Word File" Name="btnSelectWord" Margin="0,10,130,0" Click="btnSelectWord_Click" />         <Button HorizontalAlignment="Left" Margin="3,40,0,0" VerticalAlignment="Top" Content="View Word Doc" Width="100" Name="btnViewDoc" Click="btnViewDoc_Click" />         <DocumentViewer Grid.Row="1" Name="documentviewWord" VerticalAlignment="Top" HorizontalAlignment="Left"/>     </Grid>   

Step 5. Handle the events in behind class.

C#

/// <summary>         ///  Select Word file          /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void btnSelectWord_Click(object sender, RoutedEventArgs e)         {             // Initialize an OpenFileDialog             OpenFileDialog openFileDialog = new OpenFileDialog();                 // Set filter and RestoreDirectory             openFileDialog.RestoreDirectory = true;             openFileDialog.Filter = "Word documents(*.doc;*.docx)|*.doc;*.docx";                 bool? result =openFileDialog.ShowDialog();             if (result==true)             {                 if (openFileDialog.FileName.Length > 0)                 {                     txbSelectedWordFile.Text = openFileDialog.FileName;                 }             }         }             /// <summary>         ///  Convert the word document to xps document         /// </summary>         /// <param name="wordFilename">Word document Path</param>         /// <param name="xpsFilename">Xps document Path</param>         /// <returns></returns>         private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)         {             // Create a WordApplication and host word document             Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();             try             {                 wordApp.Documents.Open(wordFilename);                                  // To Invisible the word document                 wordApp.Application.Visible = false;                     // Minimize the opened word document                 wordApp.WindowState = WdWindowState.wdWindowStateMinimize;                     Document doc = wordApp.ActiveDocument;                     doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS);                     XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);                 return xpsDocument;             }             catch (Exception ex)             {                 MessageBox.Show("Error occurs, The error message is  " + ex.ToString());                 return null;             }             finally             {                 wordApp.Documents.Close();                 ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges);             }         }             /// <summary>         ///  View Word Document in WPF DocumentView Control         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void btnViewDoc_Click(object sender, RoutedEventArgs e)         {             string wordDocument =txbSelectedWordFile.Text;             if (string.IsNullOrEmpty(wordDocument) || !File.Exists(wordDocument))             {                 MessageBox.Show("The file is invalid. Please select an existing file again.");             }             else             {                 string convertedXpsDoc = string.Concat(Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");                 XpsDocument xpsDocument =ConvertWordToXps(wordDocument, convertedXpsDoc);                 if (xpsDocument == null)                 {                     return;                 }                     documentviewWord.Document = xpsDocument.GetFixedDocumentSequence();             }         }   

转自http://code.msdn.microsoft.com/office/CSVSTOViewWordInWPF-db347436/

转载于:https://www.cnblogs.com/flovel/p/3919515.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值