.NET 4.8.1安装KB5020880后FlowDocument转XPS本地图片不显示求助
解决KB5020880更新后FlowDocument转XPS本地图片不显示的问题
2022年12月13日微软针对.NET 4.8.1发布的Windows更新KB5020880(对应CVE-2022-41089),修复了XPS相关安全漏洞,但同时引发兼容性问题:将包含本地路径图片的FlowDocument渲染为XPS时,图片无法正常显示,动态创建并嵌入本地图片的场景受影响尤为明显。
用户提供的FlowDocument代码示例:
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" PageHeight="29.7cm" PageWidth="21cm" > <Section Padding="40,0,20,0"> <Paragraph>before image</Paragraph> <Paragraph FontSize="10" FontFamily="Verdana"> <Image Source="c:/Test/MyImage.jpg" Margin="40,40,0,0" /> </Paragraph> <Paragraph>after image</Paragraph> </Section> </FlowDocument>
转换为XpsDocument后,DocumentViewer中仅显示前后文本,图片区域为空,无法加载本地图片。
可行解决方案
1. 将本地图片转为流嵌入(推荐)
更新后XPS渲染限制了对本地文件系统的直接路径访问,将图片加载为内存流并直接嵌入到XPS中是最安全且有效的方案:
// 加载本地图片为BitmapImage(流模式) var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; // 确保流关闭后仍能使用 using (var stream = new FileStream(@"c:/Test/MyImage.jpg", FileMode.Open, FileAccess.Read)) { bitmap.StreamSource = stream; bitmap.EndInit(); } // 动态创建FlowDocument中的Image控件并赋值 var image = new Image { Source = bitmap, Margin = new Thickness(40, 40, 0, 0) }; // 将image添加到对应的Paragraph中
这种方式会把图片数据直接嵌入到XPS文档里,完全避开路径引用的权限问题。
2. 使用Pack URI引用应用内资源
如果图片属于应用程序的内置资源,可改用Pack URI格式引用:
- 先将图片文件的生成操作设置为Resource
- 然后修改Image的Source为:
pack://application:,,,/YourAssemblyName;component/Resources/MyImage.jpg
3. 临时关闭XPS序列化安全策略(不推荐)
若需临时应急,可尝试在XPS序列化时关闭安全限制,但这会抵消更新带来的安全修复,仅建议测试场景使用:
using (var xpsDoc = new XpsDocument("output.xps", FileAccess.Write)) { var serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); serializer.SetSecurityPolicy(XpsSerializationSecurityPolicy.NoSecurityPolicy); XpsDocumentWriter.CreateXpsDocumentWriter(serializer).Write(yourFlowDocument); }
内容的提问来源于stack exchange,提问作者jaz
相关产品推荐
相关产品推荐

