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的更多相关文章

  1. Adding Form Fields to a MS Word Document

    Configuring a Word Merge in SmartSimple is a three-step process: Create the MS Word document that wi ...

  2. Send an email with format which is stored in a word document

    1. Add a dll reference: Microsoft.Office.Interop.Word.dll 2. Add the following usings using Word = M ...

  3. How to open MS word document from the SharePoint 2010 using Microsoft.Office.Interop.dll

    or this you must change the identity of word component inC:\windows\System32\comexp.mscto be interac ...

  4. How to Set Word Document Properties with C#

    Word properties shows a brief description about one document. Through properties, we can learn gener ...

  5. Handling events in an MVVM WPF application

      Posted: June 30, 2013 | Filed under: MVVM, WPF, XAML |1 Comment In a WPF application that uses the ...

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

    ps:http://waf.codeplex.com/wikipage?title=Model-View-ViewModel%20Pattern&referringTitle=Document ...

  7. Merging a WPF application into a single EXE(WPF应用程序合并成单个Exe文件)

    I always dislike handing off little applications to people. Not because I can’t, but because of the ...

  8. C# WPF Application 下的文件操作

    好气哦,电脑好烂,每天花大把的时间在等电脑反应上. 没有钱买新电脑,连组台式机的钱都没有.好气哦. 啊啊啊啊文件操作是什么鬼???C++下我都懵了,C#下好多东西要学!!!我不会!我不会!我不会!!! ...

  9. [flask初学问题]RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/

    看B站视频学习flask-SQLalchemy时,报错RuntimeError: No application found. Either work inside a view function or ...

随机推荐

  1. Content-Type一览

    文件扩展名 Content-Type(Mime-Type) 文件扩展名 Content-Type(Mime-Type) .*( 二进制流,不知道下载文件类型) application/octet-st ...

  2. Linux vsftp

    本机环境CentOS-6.6-i386-bin-DVD1.iso安装盘.安装时选择minimal模式.本机IP地址配置为192.168.0.211. 1.查询系统是否已安装了vsftpd [root@ ...

  3. Objective-C ,ios,iphone开发基础:使用第三方库FMDB连接sqlite3 数据库,实现简单的登录

    第一步:下载第三方库,点击 连接 下载, 第二部:准备数据库:按照连接&中博客的步骤实现数据库, 数据库的设计大致如下表: id        username             pas ...

  4. 【原】CentOS7上安装Xwiki8.2.1

    环境 CentOS 7内核版本为  3.10.0-327.el7.x86_64JDK8(jdk1.8.0_101)+Tomcat7.0.67+MySQL5.6.32XWIKI 8.2.1 xwiki- ...

  5. oracle--insert

    常规insert语法就不说了,还有些特殊用法 1.  insert all into table1(col1,col2) values(v1,v2) into table2(col1,col2) va ...

  6. MySQL多实例配置

    实验环境:RHEL6.4为最小化安装,mysql安装包为通用二进制安装包,版本为mysql-5.6.26 创建mysql用户 #useradd –M –s /sbin/nologin mysql #y ...

  7. 关于js中event的target和currentTarget的区别

    今天又遇到这个问题了,总是搞不清楚target和currentTarget的区别,百度搜索的时候看到一遍文章解释得很清楚,特意记录下录,以备不时之需: target与currentTarget的区别? ...

  8. 【数论-数位统计】UVa 11076 - Add Again

    Add AgainInput: Standard Input Output: Standard Output Summation of sequence of integers is always a ...

  9. hdu 2844 多重背包+单调队列优化

    思路:把价值看做体积,而价值的大小还是其本身,那么只需判断1-m中的每个状态最大是否为自己,是就+1: #include<iostream> #include<algorithm&g ...

  10. SQL Server 2005中约束

    在SQL Server 2005中有6种约束:主键约束(primary key constraint).惟一性约束(unique constraint).检查约束(check constraint). ...