1.主要代码如下:
注意:使用命名空间System.Windows.Xps.Packaging 需要引用ReachFramework.dll动态库。
using System.Windows.Xps.Packaging;
/// <summary>
/// xps文件获取txt
/// </summary>
/// <param name="strXpsPath">xps文件路径</param>
/// <returns></returns>
public static string XpsToText(string strXpsPath)
{
try
{
if (!File.Exists(strXpsPath))
return "";
string strContent = "";
System.Windows.Xps.Packaging.XpsDocument _xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(strXpsPath, System.IO.FileAccess.Read);
IXpsFixedDocumentSequenceReader fixedDocSeqReader = _xpsDocument.FixedDocumentSequenceReader;
IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0];
StringBuilder _currentText = new StringBuilder();
for (int i = 0; i < _document.FixedPages.Count; i++)
{
IXpsFixedPageReader _page = _document.FixedPages[i];
System.Xml.XmlReader _pageContentReader = _page.XmlReader;
if (_pageContentReader != null)
{
while (_pageContentReader.Read())
{
if (_pageContentReader.Name == "Glyphs")
{
if (_pageContentReader.HasAttributes)
{
if (_pageContentReader.GetAttribute("UnicodeString") != null)
{
_currentText.Append(_pageContentReader.GetAttribute("UnicodeString"));
_currentText.AppendLine("\n");
}
}
}
}
}
}
strContent = _currentText.ToString();
_xpsDocument.Close();
return strContent;
}
catch
{
return "";
}
}