【转】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的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- How to Set Word Document Properties with C#
Word properties shows a brief description about one document. Through properties, we can learn gener ...
- 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 ...
- 每天翻译一点点: WPF Application Framework (WAF)
ps:http://waf.codeplex.com/wikipage?title=Model-View-ViewModel%20Pattern&referringTitle=Document ...
- 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 ...
- C# WPF Application 下的文件操作
好气哦,电脑好烂,每天花大把的时间在等电脑反应上. 没有钱买新电脑,连组台式机的钱都没有.好气哦. 啊啊啊啊文件操作是什么鬼???C++下我都懵了,C#下好多东西要学!!!我不会!我不会!我不会!!! ...
- [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 ...
随机推荐
- VMware系统运维(一)安装Esxi
1.下载ISO文件,开始安装,如图1,直接按回车进行安装. 图1 2.按回车键继续安装,如图2所示 图2 3.选择要安装系统的磁盘,按回车继续,如图3所示 图3 4.选择对应的键盘语言,按回车继续,如 ...
- 关于Hadoop集群的搭建环境变量相关配置
在任何路径下输入HDFS中的命令都可以进行shell操作的配置: 要设置环境变量: (1) # vim /etc/profile在profile文件下面追加写入下面信息 export HADOOP_H ...
- mac 如何进入/usr/sbin目录
1.进入terminal, 输入 ls /usr/sbin 2.在finder>前往文件夹,输入路径/usr/sbin
- Linux 内核简介
Linux内核简介 一.系统架构 (1). Linux系统架构 ##用户空间: 文件系统 C库 ##内核空间: 接口 内核 (2). Linux内核架构 二.Linux内核源代码 下载地址 www.k ...
- ss 如何解决margin-top使父元素margin失效
给子元素设置margin-top的时候父元素的也会受影响.会产生子元素和父元素margin合并的问题. 解决办法: 给父元素设置padding.或者border把父子的margin之间隔开. 一般来说 ...
- php-fpm配置文件详解
第一部分:FPM 配置 参数 | 说明 -p | 命令行中动态修改--prefix ;include=etc/fpm.d/*.conf | 用于包含一个或多个文件,如果glob(3)存在(glob() ...
- Spring(3.2.3) - Beans(2): 属性注入 & 构造注入
依赖注入是指程序运行过程中们如果需要另外的对象协作(访问它的属性或调用它的方法)时,无须在代码中创建被调用者,而是依赖于外部容器的注入. 属性注入(Setter Injection) 属性注入是指 I ...
- Git CMD - fetch: Download objects and refs from another repository
命令格式 git fetch [<options>] [<repository> [<refspec>…]] git fetch [<options> ...
- C#解析Json格式数据小结
最近,遇到了一些不同的Json格式的数据,需要做不同处理才能转化为想要得到的结果,这里总结一下. 第一种形式:status中是{}形式,对象 string json = @"{'name': ...
- 4月1日学习笔记(CSS基础)
CSS初始化 内边距padding padding属性宽度是按照上右下左的顺序来的,否则单独设置就是padding-left... 边框border border可以设置样式(border-style ...