【转】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 ...
随机推荐
- Server Tomcat v7.0 Server at localhost failed to start.错误可能原因之一
故事由来: 学Servlet中,突然发现启动Tomcat时出现这个问题 故事梗概: 学习servlet尽然能碰到服务器起不来的,百思不得其解,然后我百度,我FQgoogle,找stackoverflo ...
- SSIS 学习(3):数据流任务(下)【转】
前一篇文章SSIS 学习(2):数据流任务(上), 介绍了如何创建一个简单的ETL包,如何通过一个简单的数据流任务,将一个文本文件的数据导入到数据库中去.这些数据都保持了它原有的本色,一个字符不 多, ...
- android网络请求之POST方法
package com.jredu.helloworld.activity; import android.os.Bundle; import android.os.Handler; import a ...
- jsp无法支持el标签及jstl标签
在jsp页面头部添加如下 <%@ page isELIgnored="false"%> <%@ taglib uri="http://java.sun. ...
- Hive的JDBC使用&并把JDBC放置后台运行
使用JDBC访问HIVE: 首先启动hive的JDBC服务. 进入hive的bin目录: 这样启动是启动到前台.如果 要想启动到后台需要用到Linux的相关命令. 我们先把其放到前台看下效果,之后再把 ...
- 关于网络连接方式的总结(HostOnly,NAT....)
真实的网络结构: 最左侧的电脑左侧的线代表,如果这台电脑有网卡的话可以去连接别的电脑. 在一台Windows中用VMware来安装一个Linux系统(用虚线的都代表不是真实的) 上图中的虚拟网关在哪里 ...
- poj 3544 Journey with Pigs
Journey with Pigs Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3004 Accepted: 922 ...
- Codevs 3729==洛谷P1941 飞扬的小鸟
P1941 飞扬的小鸟 456通过 2.4K提交 题目提供者该用户不存在 标签动态规划2014NOIp提高组 难度提高+/省选- 提交该题 讨论 题解 记录 题目描述 Flappy Bird 是一 ...
- Android之布局
Android中的布局分为六种,分别是相对布局.线性布局.表格布局.网格布局.帧布局.绝对布局,良好的布局设计对UI界面至关重要,下面先来看看先相对布局. 相对布局(RelativeLayout): ...
- ASP连接ACCESS数据库
Set conn2 = Server.CreateObject("ADODB.Connection") conn2.Open "Provider=Microsoft.Je ...