从Word文档获取页码

赫兹格斯

我使用的是GemBox.Document,我需要找出Word文档中我的书签在哪一页上。能做到吗?如果不是,那么我能找到某些特定文本所在的页面吗?

我可以同时找到书签和文本,但是看不到任何可以让我从中获取页码的选项。

DocumentModel document = DocumentModel.Load("My Document.docx");
Bookmark bookmark = document.Bookmarks["My Bookmark"];
ContentRange content = document.Content.Find("My Text").First();
马里奥Z

对于Word文件,这是一项不常见的任务,您会看到这些文件本身没有页面概念,它们是流文档类型,页面概念特定于呈现它的Word应用程序(例如Microsoft Word)。

流文档类型(DOC,DOCX,RTF,HTML等格式)以可流的方式定义内容,其目的是为了简化编辑。
另一方面,固定文档类型(PDF,XPS等格式)具有页面概念,因为内容是固定的,它指定将在哪个页面和哪个位置上呈现某些特定内容,并且将其设计为呈现在任何应用程序或任何屏幕上查看时都一样。

但是,这是ContentPosition使用GemBox.Document从某些页面中获取页码的方法:

static int GetPageNumber(ContentPosition position)
{
    DocumentModel document = position.Parent.Document;

    Field pageField = new Field(document, FieldType.Page);
    Field importedPageField = position.InsertRange(pageField.Content).Parent as Field;

    document.GetPaginator(new PaginatorOptions() { UpdateFields = true });

    int pageNumber = int.Parse(importedPageField.Content.ToString());
    importedPageField.Content.Delete();

    return pageNumber;
}

另外,这是使用方法:

DocumentModel document = DocumentModel.Load("My Document.docx");
Bookmark bookmark = document.Bookmarks["My Bookmark"];
ContentRange content = document.Content.Find("My Text").First();

int bookmarkPageNumber = GetPageNumber(bookmark.Start.Content.Start);
int contentPageNumber = GetPageNumber(content.Start);

最后,请注意,该GetPaginator方法是一项繁重的工作(基本上,它类似于将整个文档保存为PDF),当您拥有相当大的文档时,它可能会很昂贵。

因此,如果您需要使用GetPageNumber多次(例如,找出您拥有的每个书签的页码),则应考虑更改代码,以便首先导入所需的所有页面字段,然后调用GetPaginator方法仅读取一次,然后读取所有这些页面字段的内容。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章