【转】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/

【转】How to view word document in WPF application

时间: 2024-10-22 21:18:30

【转】How to view word document in WPF application的相关文章

How to Set Word Document Properties with C#

Word properties shows a brief description about one document. Through properties, we can learn general information about this document, such as document size, date to create and so on. Also, we can set advance properties by ourselves, for example, ad

Difference between List View and DataGrid in WPF

Well, in WPF the difference between ListView and DataGrid is just one. Editing. You need editing use DataGrid, otherwise use ListView. You can edit in ListView also but it is easier and build in DataGrid. Otherwise, whatever can be displayed in DataG

word:Can&#39;t find the word document templant:WordToRqm.doc

问题:打开word文件时弹出提示 Cannot find the Word template:WordToRqm.dot 原因:安装了power designer. 解决:运行regedit.exe 打开注册表编辑器,定位到:HKEY_CURRENT_USER\Software\Microsoft\Office\Word\Addins\WordToRQM12.Connect 键,    双击右边的“LoadBehavior”,在弹出的修改值对话框中将其值从3改为2,然后关闭注册表编辑器,重新启动

【翻译自mos文章】 怎么对Microsoft (Office) Word Document 2007 索引化?

怎么对Microsoft (Office) Word Document 2007 索引化? 来源于:How To Index a Microsoft (Office) Word Document 2007 ? (文档 ID 752710.1) 适用于: Oracle Text - Version: 11.1.0.7 to 11.2.0.3 - Release: 11.1 to 11.2 Information in this document applies to any platform. 目

每天翻译一点点: WPF Application Framework (WAF)

ps:http://waf.codeplex.com/wikipage?title=Model-View-ViewModel%20Pattern&referringTitle=Documentation Model-View-ViewModel Pattern Common abbreviations: M-V-VM or MVVM Introduction Separating user interface code from everything else is a key principl

C# WPF Application 下的文件操作

好气哦,电脑好烂,每天花大把的时间在等电脑反应上. 没有钱买新电脑,连组台式机的钱都没有.好气哦. 啊啊啊啊文件操作是什么鬼???C++下我都懵了,C#下好多东西要学!!!我不会!我不会!我不会!!!啊啊啊啊啊啊!!! 怎么办啊?用windows API写我要怎么样移植到Linux下? WINDOWS API的文件操作 一.常用函数 CreateFile 创建.打开文件 ReadFile 读取文件内容 WriteFile 写入文件内容 SetFilePointer 移动文件指针 SetEndOf

c#学习笔记之WPF Application和Windows Form Applications

一.WPF Application WPF使用XAML(extensible application markup language)可扩展应用程序标记语言,来进行页面的操纵,非常简便易懂. 下面一段代码,就是使用xaml语言对页面进行布局 <Window x:Class="WpfApplication1.Window1"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 

WPF Application Framework (WAF)

ViewModel: public abstract class ViewModel<TView> : ViewModel where TView : IView WPF Application Framework (WAF)

vs 编译错误 The name &#39;InitializeComponent&#39; does not exist in the current context in WPF application

1:文件命名空间的问题 xaml文件和model.cs文件的命名空间 2:csproj 那么它究竟是给谁用的呢?那是给开发工具用的,例如我们在熟悉不过的Visual Studio,以及大家可以没有接触过,但是应该都听说过的MSBuild.exe.Visual Studio会根据csproj里的XML定义来管理项目文件以及相关其他一些种类非常丰富的数据及操作,MSBuild也会根据csproj文件来得知编译这个项目需要有哪些依赖,默认输出路径,Pre-Build和Post-Build需要哪些操作等