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. hdfs: 一个分布式文件系统(一)

    一. hdfs设计的动机 为大规模分布式计算准备的分布式文件系统,并非实时性要求很高的文件系统. 二. 设计的取舍 1. 因为要求有高吞吐量,所以牺牲读取文件的实时性,实时性要求高的分布式文件系统可以 ...

  2. jQuery扩展工具方法

    共享学习Jquery源码的一些东西 jQuery.extend({   expando  :  生成唯一JQ字符串(内部) noConflict()  :  防止冲突 ---------------- ...

  3. Android 自学之选项卡TabHost

    选项卡(TabHost)是一种非常实用的组件,TabHost可以很方便地在窗口上放置多个标签页,每个标签页相当于获得了一个与外部容器相同大小的组建摆放区域.通过这种方式,就可以在一个容器中放置更多组件 ...

  4. MapReduce按照两个字段对数据进行排序

    按照k2排序,要求k2必须是可以比较的,即必须实现WritableComparable接口. 但是如果还想让别的字段(比如v2中的一些字段)参与排序怎么办? 需要重新定义k2....把需要参与排序的字 ...

  5. 我的jquery之路

    不知不觉jquery已经看完了. 以前不知道jquery是什么,现在依然不是很清晰.或许学习的结果就是这样吧,忘记你所学的.

  6. ActiveMQ(5.10.0) - Spring Support

    Maven Dependency: <dependencies> <dependency> <groupId>org.apache.activemq</gro ...

  7. MyBatis(3.2.3) - Configuring MyBatis using XML, Properties

    The properties configuration element can be used to externalize the configuration values into a prop ...

  8. Android Studio 创建aar包与引用

    两者区别:*.jar: 只包含了class文件与清单文件 ,不包含资源文件,如图片等所有res中的文件.*.aar: 包含所有资源 ,class以及res资源文件全部包含 一.创建aar包1.创建一个 ...

  9. SQL Server 编程入门经典(3)之T-SQL基本语句

    本章内容简介: 如何从数据库检索数据(SELECT) 如何向表中插入数据(INSERT) 如何适当更新数据(UPDATE) 如何删除表中数据(DELETE) 3.1 基本SELECT语句  如果你在此 ...

  10. Insert data from excel to database

    USE ESPA Truncate table dbo.Interface_Customer --Delete the table data but retain the structure exec ...