0

我在研究时一直在运行此代码,但是将其复制到我的表单中会给我一个错误的documentViewerElement部分说The name 'documentViewerElement' does not exist in the current context

XpsDocument _xpsDocument=new XpsDocument("/path",System.IO.FileAccess.Read);
IXpsFixedDocumentSequenceReader fixedDocSeqReader 
    =_xpsDocument.FixedDocumentSequenceReader;
IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0];
IXpsFixedPageReader _page 
    = _document.FixedPages[documentViewerElement.MasterPageNumber];
StringBuilder _currentText = new StringBuilder();
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"));                              
        }
      }
    }
  }
}
string _fullPageText = _currentText.ToString();

我希望从 xps 文档中获取所有文本并将其放在富文本框中。

4

1 回答 1

2

documentViewerElement 未定义,因此您的错误。

在以下行中:

IXpsFixedPageReader _page 
= _document.FixedPages[documentViewerElement.MasterPageNumber];

documentViewerElement.MasterPageNumber 只是页码,所以改成你要阅读的xps页面,eg

IXpsFixedPageReader _page 
= _document.FixedPages[0];

要从整个 xps 文件中读取文本,您可以尝试以下操作(它与您的代码几乎相同,它只是循环(取自此处)。

private string ReadXpsFile(string fileName)
{
    XpsDocument _xpsDocument = new XpsDocument(fileName, System.IO.FileAccess.Read);
    IXpsFixedDocumentSequenceReader fixedDocSeqReader = _xpsDocument.FixedDocumentSequenceReader;
    IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0];
    FixedDocumentSequence sequence = _xpsDocument.GetFixedDocumentSequence();
    string _fullPageText="";

    for (int pageCount = 0; pageCount < sequence.DocumentPaginator.PageCount; ++pageCount)
    {
        IXpsFixedPageReader _page = _document.FixedPages[pageCount];
        StringBuilder _currentText = new StringBuilder();
        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"));
                        }
                    }
                }
            }
        }

        _fullPageText += _currentText.ToString();
    }

    return _fullPageText;
}
于 2015-08-12T10:28:44.283 回答