FlowDocument中缺少的图像保存为XPS文档

Jak*_*sen 7 wpf xpsdocument image flowdocument

我在获取FlowDocument中包含的图像时遇到一些困难,以显示FlowDocument何时保存为XPS文档.

这是我做的:

  1. 使用WPF 的Image控件创建图像.我通过调用BeginInit/EndInit设置了括号的图像源.
  2. 将图像添加到FlowDocument中,将其包装在BlockUIContainer中.
  3. 使用此代码的修改版本将FlowDocument对象保存到XPS文件.

如果我然后在XPS查看器中查看保存的文件,则不显示图像.问题是,在WPF实际显示在屏幕上之前不会加载图像,因此它们不会保存到XPS文件中.因此,有一种解决方法:如果我首先使用FlowDocumentPageViewer在屏幕上显示文档,然后保存XPS文件,则会加载图像并显示在XPS文件中.即使隐藏了FlowDocumentPageViewer,这也可以工作.但这给了我另一个挑战.这是我想做的(在伪代码中):

void SaveDocument()
{
    AddFlowDocumentToFlowDocumentPageViewer();
    SaveFlowDocumentToXpsFile();
}
Run Code Online (Sandbox Code Playgroud)

这当然不起作用,因为在文档保存到XPS文件之前,FlowDocumentPageViewer永远不会有机会显示其内容.我尝试在调用Dispatcher.BeginInvoke时包装SaveFlowDocumentToXpsFile但它没有帮助.

我的问题是:

  1. 在保存XPS文件之前,我是否可以以某种方式强制图像加载而不实际在屏幕上显示文档?(我试着摆弄BitmapImage.CreateOptions而没有运气).
  2. 如果没有问题#1的解决方案,有没有办法告诉FlowDocumentPageViewer何时完成加载其内容,以便我知道何时保存以创建XPS文件?

Den*_*nis 3

最终的解决方案与您遇到的相同,即将文档放入查看器中并在屏幕上短暂显示。下面是我为我编写的辅助方法。

private static string ForceRenderFlowDocumentXaml = 
@"<Window xmlns=""http://schemas.microsoft.com/netfx/2007/xaml/presentation""
          xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
       <FlowDocumentScrollViewer Name=""viewer""/>
  </Window>";

public static void ForceRenderFlowDocument(FlowDocument document)
{
    using (var reader = new XmlTextReader(new StringReader(ForceRenderFlowDocumentXaml)))
    {
        Window window = XamlReader.Load(reader) as Window;
        FlowDocumentScrollViewer viewer = LogicalTreeHelper.FindLogicalNode(window, "viewer") as FlowDocumentScrollViewer;
        viewer.Document = document;
        // Show the window way off-screen
        window.WindowStartupLocation = WindowStartupLocation.Manual;
        window.Top = Int32.MaxValue;
        window.Left = Int32.MaxValue;
        window.ShowInTaskbar = false;
        window.Show();
        // Ensure that dispatcher has done the layout and render passes
        Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Loaded, new Action(() => {}));
        viewer.Document = null;
        window.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚添加window.ShowInTaskbar = false到该方法中,就好像您很快就可以看到该窗口出现在任务栏中一样。

用户永远不会“看到”窗口,因为它位于远离屏幕的位置Int32.MaxValue- 这是早期多媒体创作(例如 Macromedia/Adobe Director)中常见的技巧。

对于搜索和找到这个问题的人,我可以告诉您,没有其他方法可以强制渲染文档。

哈特哈,