WFP: 读取XPS文件或将word、txt文件转化为XPS文件
读取XPS格式文件或将doc,txt文件转化为XPS文件,效果图如下:
1.XAML页面代码:
<Window x:Class="WpfWord.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WordReader" Height="500" Width="900">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0" Name="cdTree"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<GroupBox Header="导航目录">
<TreeView Name="tvTree" SelectedItemChanged="tvTree_SelectedItemChanged"/>
</GroupBox>
<GridSplitter Width="3" ResizeBehavior="PreviousAndNext" Grid.Column="1" Background="LightGray"/>
<Grid Grid.Column="3">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DocumentViewer Name="dvShow" Grid.Row="1"/>
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right">
<CheckBox Content="显示导航" Height="16" Margin="5" Name="cbNav" Width="75" Click="cbNav_Click" />
<Label Content="页面"/>
<Label Name="lblCurPage" Margin="0"/>
<Label Name="lblPage"/>
<Button Content="上一页" Height="23" Name="btnPrev" Width="75" Click="btnPrev_Click" />
<Button Content="下一页" Height="23" Name="btnNext" Width="75" Click="btnNext_Click" />
<Label Content="总字数:" Name="lblWordCount"/>
</StackPanel>
</Grid>
</Grid>
</Window>
2.后台CS文件代码:
首先引用Microsoft.Office.Interop.Word.dll;
//具体代码如下↓
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
using System.Xml;
using Microsoft.Office.Interop.Word;
namespace WpfWord
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : System.Windows.Window
{
#region 全局变量
/// <summary>
/// 用于存放目录文档各节点OutlineLevel值,并转化为int型
/// </summary>
int[] array = null;
/// <summary>
/// 用于存放目录文档各节点OutlineLevel值
/// </summary>
string[] array1 = null;
/// <summary>
/// 用于存放目录文档各节点Description值,章节信息
/// </summary>
string[] arrayName = null;
/// <summary>
/// 用于存放目录文档各节点OutlineTarget值,页码信息
/// </summary>
string[] pages = null;
#endregion
public MainWindow()
{
InitializeComponent();
OpenFile(null);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="strFilePath">文件路径</param>
public MainWindow(string strFilePath)
: this()
{
}
#region 方法
/// <summary>
/// 读取导航目录
/// </summary>
private void ReadDoc(XpsDocument xpsDoc)
{
IXpsFixedDocumentSequenceReader docSeq = xpsDoc.FixedDocumentSequenceReader;
IXpsFixedDocumentReader docReader = docSeq.FixedDocuments[0];
XpsStructure xpsStructure = docReader.DocumentStructure;
Stream stream = xpsStructure.GetStream();
XmlDocument doc = new XmlDocument();
doc.Load(stream);
//获取节点列表
XmlNodeList nodeList = doc.ChildNodes.Item(0).FirstChild.FirstChild.ChildNodes;
if (nodeList.Count <= 0)//判断是否存在目录节点
{
//tvTree.Visibility = System.Windows.Visibility.Hidden;
tvTree.Items.Add(new TreeViewItem { Header = "没有导航目录" });
return;
}
tvTree.Visibility = System.Windows.Visibility.Visible;
array = new int[nodeList.Count];
array1 = new string[nodeList.Count];
arrayName = new string[nodeList.Count];
pages = new string[nodeList.Count];
for (int i = 0; i < nodeList.Count; i++)
{
array[i] = Convert.ToInt32(nodeList[i].Attributes["OutlineLevel"].Value);
array1[i] = nodeList[i].Attributes["OutlineLevel"].Value.ToString();
arrayName[i] = nodeList[i].Attributes["Description"].Value.ToString();
pages[i] = nodeList[i].Attributes["OutlineTarget"].Value.ToString();
}
for (int i = 0; i < array.Length - 1; i++)
{
//对array进行转换组装成可读的树形结构,通过ASCII值进行增加、转换
array1[0] = "A";
if (array[i + 1] - array[i] == 1)
{
array1[i + 1] = array1[i] + 'A';
}
if (array[i + 1] == array[i])
{
char s = Convert.ToChar(array1[i].Substring((array1[i].Length - 1), 1));
array1[i + 1] = array1[i].Substring(0, array1[i].Length - 1) + (char)(s + 1);
}
if (array[i + 1] < array[i])
{
int m = array[i + 1];
char s = Convert.ToChar(array1[i].Substring(0, m).Substring(m - 1, 1));
array1[i + 1] = array1[i].Substring(0, m - 1) + (char)(s + 1);
}
}
//添加一个节点作为根节点
TreeViewItem parent = new TreeViewItem();
TreeViewItem parent1 = null;
parent.Header = "目录导航";
Boolean flag = false;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == 1)
{
flag = true;
}
if (flag) //如果找到实际根节点,加载树
{
parent1 = new TreeViewItem();
parent1.Header = arrayName[i];
parent1.Tag = array1[i];
parent.Items.Add(parent1);
parent.IsExpanded = true;
parent1.IsExpanded = true;
FillTree(parent1, array1, arrayName);
flag = false;
}
}
tvTree.Items.Clear();
tvTree.Items.Add(parent);
}
/// <summary>
/// 填充树的方法
/// </summary>
/// <param name="parentItem"></param>
/// <param name="str1"></param>
/// <param name="str2"></param>
public void FillTree(TreeViewItem parentItem, string[] str1, string[] str2)
{
string parentID = parentItem.Tag as string;
for (int i = 0; i < str1.Length; i++)
{
if (str1[i].IndexOf(parentID) == 0 && str1[i].Length == (parentID.Length + 1) && str1[i].ElementAt(0).Equals(parentID.ElementAt(0)))
{
TreeViewItem childItem = new TreeViewItem();
childItem.Header = str2[i];
childItem.Tag = str1[i];
parentItem.Items.Add(childItem);
FillTree(childItem, str1, str2);
}
}
}
/// <summary>
/// 打开文件-如果传入路径为空则在此打开选择文件对话框
/// </summary>
/// <param name="strFilepath">传入文件全路径</param>
private void OpenFile(string strFilepath)
{
if (string.IsNullOrEmpty(strFilepath))
{
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.DefaultExt = ".doc|.txt|.xps";
openFileDialog.Filter = "*(.xps)|*.xps|Word documents (.doc)|*.doc|Word(2007-2010)(.docx)|*.docx|*(.txt)|*.txt";
Nullable<bool> result = openFileDialog.ShowDialog();
strFilepath = openFileDialog.FileName;
if (result != true)
{
return;
}
}
this.Title = strFilepath.Substring(strFilepath.LastIndexOf("\\")+1);
if (strFilepath.Length > 0)
{
XpsDocument xpsDoc = null;
//如果是xps文件直接打开,否则需转换格式
if (!strFilepath.EndsWith(".xps"))
{
string newXPSdocName = String.Concat(System.IO.Path.GetDirectoryName(strFilepath), "\\", System.IO.Path.GetFileNameWithoutExtension(strFilepath), ".xps");
xpsDoc = ConvertWordToXPS(strFilepath, newXPSdocName);
}
else
{
xpsDoc = new XpsDocument(strFilepath, System.IO.FileAccess.Read);
}
if (xpsDoc != null)
{
dvShow.Document = xpsDoc.GetFixedDocumentSequence();
//读取文档目录
ReadDoc(xpsDoc);
xpsDoc.Close();
}
this.lblCurPage.Content = 0;
this.lblPage.Content = "/" + dvShow.PageCount;
}
}
/// <summary>
/// 将word文档转换为xps文档
/// </summary>
/// <param name="wordDocName">word文档全路径</param>
/// <param name="xpsDocName">xps文档全路径</param>
/// <returns></returns>
private XpsDocument ConvertWordToXPS(string wordDocName, string xpsDocName)
{
XpsDocument result = null;
//创建一个word文档,并将要转换的文档添加到新创建的对象
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
try
{
wordApplication.Documents.Add(wordDocName);
Document doc = wordApplication.ActiveDocument;
doc.ExportAsFixedFormat(xpsDocName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, true, true, false, Type.Missing);
result = new XpsDocument(xpsDocName, System.IO.FileAccess.ReadWrite);
}
catch (Exception ex)
{
string error = ex.Message;
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
}
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
return result;
}
#endregion
/// <summary>
/// 导航树跳转事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
int x = 0;
TreeViewItem selectTV = this.tvTree.SelectedItem as TreeViewItem;
if (null == selectTV)
return;
if (null == selectTV.Tag)
return;
string page = selectTV.Tag.ToString();
for (int i = 0; i < array1.Length; i++)
{
if (array1[i].Equals(page))
{
x = i;
}
}
string[] strPages = pages[x].Split('_');
dvShow.GoToPage(Int32.Parse(strPages[1]));
}
private void cbNav_Click(object sender, RoutedEventArgs e)
{
this.cdTree.Width = this.cbNav.IsChecked == true ? new GridLength(300) : new GridLength(0);
}
private void btnPrev_Click(object sender, RoutedEventArgs e)
{
this.dvShow.PreviousPage();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
this.dvShow.NextPage();
}
}
}
WFP: 读取XPS文件或将word、txt文件转化为XPS文件的更多相关文章
- 【文件】使用word的xml模板生成.doc文件
一.编辑模板 替换地方以变量标记如“案件编号”可写成{caseNo} template.xml 二.准备数据 以HashMap封装数据,原理是替换模板中的变量 三.替换操作 选择输出位置:writeP ...
- 怎样将word文件转化为Latex文件:word-to-latex-2.56具体解释
首先推荐大家读一读这篇博文:http://blog.csdn.net/ibingow/article/details/8613556 --------------------------------- ...
- WPF: 读取XPS文件或将word、txt文件转化为XPS文件
读取XPS格式文件或将doc,txt文件转化为XPS文件,效果图如下: 1.XAML页面代码: <Window x:Class="WpfWord.MainWindow" xm ...
- c#上传文件并将word pdf转化成txt存储并将内容写入数据库
c#上传文件并将word pdf转化成txt存储并将内容写入数据库 using System; using System.Data; using System.Configuration; using ...
- Python:读取 .doc、.docx 两种 Word 文件简述及“Word 未能引发事件”错误
概述 Python 中可以读取 word 文件的库有 python-docx 和 pywin32. 下表比较了各自的优缺点. 优点 缺点 python-docx 跨平台 只能处理 .docx 格式 ...
- python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件
python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 python操作txt文件中 ...
- c# 读取 excel文件内容,写入txt文档
1 winform 读取excel文档 1)点击button按钮,弹出上传excel窗口 private void button_headcompany_Click(object sender, Ev ...
- 逐行创建、读取并写入txt(matlab) && 生成文件夹里文件名的.bat文件
fidin=fopen('C:\Users\byte\Desktop\新建文件夹 (4)\tr4.txt','r'); fidout=fopen('C:\Users\byte\Desktop\新建文件 ...
- 软件工程第三个程序:“WC项目” —— 文件信息统计(Word Count ) 命令行程序
软件工程第三个程序:“WC项目” —— 文件信息统计(Word Count ) 命令行程序 格式:wc.exe [parameter][filename] 在[parameter]中,用户通过输入参数 ...
随机推荐
- Windows环境下安装Redis
1:首先下载redis.从下面地址下:https://github.com/MSOpenTech/redis/releases2:创建redis.conf文件:这是一个配置文件,指定了redis的监听 ...
- 一次PostgreSql数据迁移,使用nodejs来完成
2014-02-08 XX开放平台不允许使用站外的服务器了,可是我们的app都在站外,数据库也在站外,全都要求迁移到其云主机上(坑爹啊).我们在其云主机上仅有有限的资源,而且也有在运行中的数据库,要做 ...
- Android小项目之九 两种上下文的区别
------- 源自梦想.永远是你IT事业的好友.只是勇敢地说出我学到! ---------- 按惯例,写在前面的:可能在学习Android的过程中,大家会和我一样,学习过大量的基础知识,很多的知识点 ...
- iOS UINavigationController 详解
developer.apple.com/cn/ 导航条 UINavigationBar继承UIView 导航控制器 UINavigationController (压栈,出栈) ...
- 递归删除指定目录下的 .git 文件
转载自:http://my.oschina.net/armsky/blog/34447 find . -name .git | xargs rm -fr 其中对 xargs 的介绍,可以参照以下内容: ...
- 新浪SAE部署django博客
步骤: 第一步:注册新浪SAE账号(即新浪微博),下载TortoiseSVN 第二步:部署代码 使用SAE来部署代码,SAE提供的是PAAS层的云服务,即不是给你一个虚拟主机而是直接上传应用.进入SA ...
- 一路踩过的坑 php
1.数据表唯一索引 (两列字段,组合索引) 遇到的情形:项目搭建新测试环境(其实就是所谓的灰度 与线上一致的一个环境):从线上拉回来代码搭建的,数据也是来自于线上数据,但是由于线上数据有部分为机密数 ...
- 人体时钟hone hone clock
摘要:一个由日本人设计的有意思的Flash时钟:人体时钟 hone hone clock .安装很简单,直接js导入即可,包括两种样式:透明背景和白色背景. 很可爱的一个设计,实现后效果如下: 使用方 ...
- 2013 长沙网络赛J题
思路:这题对于其他能退出所有值的情况比较好像,唯一不能确定的是XXOXXOXXOXX这个形式的序列,其中XX表示未知,O表示已知. 我们令num[1]=0,那么num[4]=sum[3]-sum[2] ...
- vijos 1053Easy sssp
P1053Easy sssp Accepted 标签:图结构 最短路 描述 输入数据给出一个有N(2 <= N <= 1,000)个节点,M(M <= 100,000)条边的 ...