WinForms/WPFビューアでのDOCXページの遅延読み込み

ブログ カテゴリ: イメージングOffice.NET

2024/04/19

DOCXドキュメントは、テキスト、画像、グラフィックなどを含むMicrosoft Word Open XML形式のドキュメントです。DOCXドキュメントの利点は、コンテンツをシンプルで直感的に編集できることです。DOCXドキュメントの欠点は、ドキュメントのコンテンツをページに分割するためにレイアウトする必要があることです。つまり、1000ページのDOCXドキュメントの場合、最後のページのみを表示する必要がある場合でも、ドキュメントのすべてのページをレンダリングする必要があります。

Microsoft Office Word でページ数の多い (1000 ページ以上) DOCX 文書を開くと、Word がほぼ瞬時に DOCX 文書を開き、数ページ (3 ~ 5 ページ) しか表示しないことがわかります。その後、バックグラウンドで、文書の残りのすべてのページが Word によって読み込まれます。これは、Word が DOCX 文書のすべてのページをレイアウトするまでユーザーが待たなくて済むようにするためです。レイアウトにはかなり長い時間がかかることがあります。DOCX ページのバックグラウンド読み込みは非常に便利です。ユーザーは文書の先頭からすぐに表示および編集を開始できます。文書の最後のページを表示または編集する必要がある場合は、Word が文書のすべてのページを読み込むまで待つ必要があります。

VintaSoft Imaging .NET SDK を使用すると、DOCX 文書を表示できます。デフォルトでは、SDK は DOCX 文書のすべてのページに関する情報を取得し、その後でのみ、DOCX 文書のページをドキュメント ビューアーで表示できます。大きな DOCX ドキュメント (1000 ページ以上) の場合、すべてのページに関する情報が取得されるまで待機する必要があり、その後でのみページを表示できるため、これは便利ではありません。

また、VintaSoft Imaging .NET SDK では、Microsoft Office Word の動作を再現して、バックグラウンドで DOCX ドキュメントのページに関する情報を取得できます。画像コレクションのページ/画像に関する情報のバックグラウンド取得を有効にするには、[ImageViewerImagesManager] クラスを使用し、そのクラスを次のように指定する必要があります。

バックグラウンドで DOCX ドキュメント ページ情報を読み込みながら、ドキュメント ビューアーに DOCX ドキュメント ページを表示できる C# コードは次のとおりです:
/// <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");
}