I want to display xps Image in DocumentViewer, but without success.
Does DocumentViewer support displaying images?
If it is possible to display a picture in DocumentView, how can I do it?
Any reply will be helpful.
My code is as follows:
<StackPanel Orientation="Horizontal" >
<FlowDocumentReader Height="150" Width="170">
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<Grid>
<Image Source="C:\Users\Admin\Downloads\XpsTest-main\XpsTest-main\33.jpg" Width="200" Height="200" />
<TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Red" />
</Grid>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<StackPanel>
<Button Click="Button_Click" Content="save"/>
<Button Click="Button_Click_1" Content="show"/>
</StackPanel>
<DocumentViewer Name="viewer" Width="600"/>
</StackPanel>
C#
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
namespace XpsTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void PrintVisual(Visual visual)
{
PrintDocumentImageableArea imageArea = null;
XpsDocumentWriter xpdw = PrintQueue.CreateXpsDocumentWriter(ref imageArea);
if (xpdw != null)
{
xpdw.Write(visual);
}
}
public static void SaveAsXps(string path, FlowDocument document)
{
using (var package = Package.Open(path, FileMode.Create))
{
using (var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum))
{
var xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
var documentPaginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
xpsSerializationManager.SaveAsXaml(documentPaginator);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveAsXps(@"C:\Users\Admin\Desktop\temp.xps", flowDocument);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
XpsDocument xpsDocument = new XpsDocument(@"C:\Users\Admin\Desktop\temp.xps", FileAccess.Read);
FixedDocumentSequence fds = xpsDocument.GetFixedDocumentSequence();
viewer.Document = fds;
}
}
}
Test the above code, the picture cannot be displayed normally in DocumentView.
I used the exact same code to test in .NetFramework 4.8 and in .NET6 respectively. It doesn't show pictures in .NetFramework 4.8 and shows pictures in .NET6(.NET5).
Codebehind:
The result in .NetFramework 4.8 :
The result in .NET6(.NET5) :
