在 WinForms/WPF 查看器中延迟加载 DOCX 页面

博客类别:成像办公.NET

2024/04/19

DOCX 文档是一种 Microsoft Word Open XML 格式文档,包含文本、图像、图形等。DOCX 文档的优点是内容编辑简单直观。缺点是需要对文档内容进行排版才能将其分成页面。换句话说,对于一个 1000 页的 DOCX 文档,即使您只需要查看最后一页,也需要渲染所有页面。

如果您在 Microsoft Office Word 中打开一个包含大量页面(1000 页或更多)的 DOCX 文档,您会注意到 Word 几乎立即打开该文档,但只显示几页(3-5 页)。之后,Word 会在后台加载文档的所有其他页面。这样做是为了避免用户等待 Word 完成 DOCX 文档所有页面的排版,因为这可能耗时较长。后台加载 DOCX 页面非常方便,因为用户可以快速开始查看和编辑文档的开头部分。如果用户需要查看或编辑文档的最后一页,则需要等待 Word 加载完所有页面。

VintaSoft Imaging .NET SDK 允许查看 DOCX 文档。默认情况下,SDK 会先检索 DOCX 文档所有页面的信息,之后才能在文档查看器中查看这些页面。对于大型 DOCX 文档(1000 页或更多),这种方式并不方便,因为必须等待所有页面的信息检索完毕才能查看页面。

此外,VintaSoft Imaging .NET SDK 允许重现 Microsoft Office Word 的行为,即在后台检索 DOCX 文档的页面信息。为了启用图像集合中页面/图像信息的后台检索,需要使用 [ImageViewerImagesManager] 类,并指定该类应执行以下操作:

以下 C# 代码允许在后台加载 DOCX 文档页面信息的同时,在文档查看器中显示 DOCX 文档页面:
/// <summary>
/// The images manager for an image viewer.
/// </summary>
Vintasoft.Imaging.UI.ImageViewerImagesManager _imagesManager;



/// <summary>
/// Initializes a new instance of the <see cref="MainForm1"/> class.
/// </summary>
public MainForm1()
{
    InitializeComponent();

    // create images manager
    _imagesManager = new Vintasoft.Imaging.UI.ImageViewerImagesManager(imageViewer1);
    // specify that manager should retrieve information about image from file during 1 second, add images to an image viewer,
    // do previous steps until information about all images will not be retrieved
    _imagesManager.IntermediateAddInterval = 1000;
    // specify that manager should work asynchronously
    _imagesManager.IsAsync = true;
    _imagesManager.ImageSourceAddException += ImagesManager_ImageSourceAddException;
}



/// <summary>
/// Opens an image file.
/// </summary>
/// <param name="filename">The filename.</param>
internal void OpenImageFile(string filename)
{
    // cancel previous file opening process
    CancelOpening();
    // clear image collection of manager
    _imagesManager.Images.ClearAndDisposeItems();
    // add image file to the manager
    _imagesManager.Add(filename);
}

/// <summary>
/// Cancels the opening of a file.
/// </summary>
private void CancelOpening()
{
    _imagesManager.Cancel();
}

private void ImagesManager_ImageSourceAddException(object sender, Vintasoft.Imaging.ImageSourceExceptionEventArgs e)
{
    string message = string.Format("Cannot open {0} : {1}", System.IO.Path.GetFileName(e.SourceFilename), e.Exception.Message);
    System.Windows.Forms.MessageBox.Show(message, "Error");
}