【转】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 ...
随机推荐
- ReactNative 大图手势浏览技术分析
支持通用的手势缩放,手势跟随,多图翻页 手势系统 通过 PanResponder.create 创建手势响应者,分别在 onPanResponderMove 与 onPanResponderRelea ...
- iOS开发:获取设备IP地址
一.导入头文件 //首先导入头文件信息 #include <ifaddrs.h> #include <arpa/inet.h> #include <net/if.h> ...
- jboss使用(eap 6.0以后版本)
以6.3版本为例,下载地址 https://www.jboss.org/products/eap/download/,这个地址现在有问题了,下不了好像要redhat账号还要花钱?不知咋回事 下载完成后 ...
- XShell提示Connection closed by foreign host的问题 和 路由器分配IP的规则
情况是这样的: VMware中有三个Linux机器分别是crxy99(192.168.1.99),crxy100(192.168.1.100),crxy101(192.168.1.101),crxy1 ...
- CSS组件化思考
为什么组件化? 分层设计,代码复用,减少冗余: 维护方便,弹性好: 如何组件化? 目前代码分成三级: 第一级粒度最细,是基础,主要包含字体配置,颜色配置,UI框架(比如MUI或者pure.css): ...
- CSS3 媒体记
css3 媒体 Media Type 媒体类型 媒体类型是CSS2中一个非常有用的属性.通过媒体类型可以对不同的设备指定不同的样式. W3C共列出十种媒体类型,如表: 值 设备类型 all 所有设备 ...
- Linux - 硬链接与软链接
在 Linux 的文件系统中,磁盘块分成了 3 个部分.一部分称为数据区,用来存放文件内容.另一部分称为 inode 表,用来存放文件属性.第三部分称为超级块,用来存放文件系统本身的属性.文件的内容和 ...
- asp.net常见面试题(一)
1.索引器 class Player { ]; public int this[int index] { get { || index >= ) { ; } else { return arr[ ...
- C# 为网络程序添加用户代理
如何为网络程序添加用户代理,本人推荐使用UrlMkSetSessionOption函数, 不过该函数有一个弱点不可以X64编译,X86编译软件才可以调用该函数 否则会一直返回!S_OK意义错误.第二呢 ...
- React-Native错误笔记-EPERM
运行react-native run-android时出现错误 EPERM:operation not permitted,lstat .............. 解决办法:用Android Stu ...