WPF: 读取XPS文件或将word、txt文件转化为XPS文件

2023-10-18 08:59
文章标签 读取 txt 转化 word wpf xps

本文主要是介绍WPF: 读取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;       #endregionpublic 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();}}
}

 

转自:http://www.cnblogs.com/_ymw/p/3324892.html

 

转载于:https://www.cnblogs.com/zxbzl/p/3923836.html

这篇关于WPF: 读取XPS文件或将word、txt文件转化为XPS文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/231568

相关文章

SpringBoot读取ZooKeeper(ZK)属性的方法实现

《SpringBoot读取ZooKeeper(ZK)属性的方法实现》本文主要介绍了SpringBoot读取ZooKeeper(ZK)属性的方法实现,强调使用@ConfigurationProperti... 目录1. 在配置文件中定义 ZK 属性application.propertiesapplicati

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷

Python使用Code2flow将代码转化为流程图的操作教程

《Python使用Code2flow将代码转化为流程图的操作教程》Code2flow是一款开源工具,能够将代码自动转换为流程图,该工具对于代码审查、调试和理解大型代码库非常有用,在这篇博客中,我们将深... 目录引言1nVflRA、为什么选择 Code2flow?2、安装 Code2flow3、基本功能演示

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

如何Python使用设置word的页边距

《如何Python使用设置word的页边距》在编写或处理Word文档的过程中,页边距是一个不可忽视的排版要素,本文将介绍如何使用Python设置Word文档中各个节的页边距,需要的可以参考下... 目录操作步骤代码示例页边距单位说明应用场景与高级用China编程途小结在编写或处理Word文档的过程中,页边距是一个

Python使用python-docx实现自动化处理Word文档

《Python使用python-docx实现自动化处理Word文档》这篇文章主要为大家展示了Python如何通过代码实现段落样式复制,HTML表格转Word表格以及动态生成可定制化模板的功能,感兴趣的... 目录一、引言二、核心功能模块解析1. 段落样式与图片复制2. html表格转Word表格3. 模板生

使用WPF实现窗口抖动动画效果

《使用WPF实现窗口抖动动画效果》在用户界面设计中,适当的动画反馈可以提升用户体验,尤其是在错误提示、操作失败等场景下,窗口抖动作为一种常见且直观的视觉反馈方式,常用于提醒用户注意当前状态,本文将详细... 目录前言实现思路概述核心代码实现1、 获取目标窗口2、初始化基础位置值3、创建抖动动画4、动画完成后

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>