当 FlowDocument 保存为 XPS 文档时,获取 FlowDocument 中包含的图像以显示时遇到一些困难。
这是我所做的:
- 使用创建图像ImageWPF 的控制。我通过对 BeginInit/EndInit 的调用将图像源设置为括起来。
- 将图像添加到 FlowDocument 中,将其包装在块UI容器.
- 使用修改版本将 FlowDocument 对象保存到 XPS 文件这段代码.
如果我随后在 XPS 查看器中查看保存的文件,则不会显示图像。问题是图像在 WPF 实际显示在屏幕上之前不会加载,因此它们不会保存到 XPS 文件中。因此,有一个解决方法:如果我首先使用流程文档页面查看器然后保存XPS文件,图像被加载并显示在XPS文件中。即使 FlowDocumentPageViewer 处于隐藏状态,此操作也有效。但这给了我另一个挑战。这是我想做的(伪代码):
void SaveDocument()
{
AddFlowDocumentToFlowDocumentPageViewer();
SaveFlowDocumentToXpsFile();
}
这当然不起作用,因为在将文档保存到 XPS 文件之前,FlowDocumentPageViewer 永远没有机会显示其内容。我尝试将 SaveFlowDocumentToXpsFile 包装在对 Dispatcher.BeginInvoke 的调用中,但没有帮助。
我的问题是:
- 我是否可以在保存 XPS 文件之前强制加载图像,而不在屏幕上实际显示文档? (我尝试摆弄位图图像.CreateOptions没有运气)。
- 如果问题#1 没有解决方案,有没有办法告诉 FlowDocumentPageViewer 何时完成加载其内容,以便我知道何时保存以创建 XPS 文件?
最终的解决方案与您遇到的相同,即将文档放入查看器中并在屏幕上短暂显示。下面是我为我编写的辅助方法。
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();
}
}
Edit:我刚刚添加了window.ShowInTaskbar = false
就好像您很快就可以看到该窗口出现在任务栏中一样。
用户永远不会“看到”窗口,因为它位于屏幕之外Int32.MaxValue
- 这是早期多媒体创作(例如 Macromedia/Adobe Director)中常见的技巧。
对于搜索和找到这个问题的人,我可以告诉你没有其他办法强制渲染文档。
HTH,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)