重现步骤
平台:WPF
.NET 版本:.NET 7
预期行为: 我的目标是打印 WPF UI 数据网格“ReportGrid”或窗口“Main”。打印代码只是为了转换/重新调整 UI 以适合一个“字母”页面。 Oxyplot 应该可以调整大小并打印。
实际行为: 打印 UI 后,您可以看到 UI 右侧的按钮已打印,但 Oxyplot 为空白且未打印。 我有另一个使用 .NET Framework 4.8 而不是 .NET 7 的应用程序。使用相同的打印代码,UI 打印工作正常。 使用 .NET 7 的 Oxyplot 库似乎存在兼容性问题,我不确定如何解决此问题或是否有解决方法?
<Window x:Class="OxyPlotPrintTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:OxyPlotPrintTest"
xmlns:oxy="http://oxyplot.org/wpf"
Title="MainWindow" Height="800" Width="1280"
Name="Main">
<Grid Name="ReportGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<oxy:PlotView x:Name="plot"/>
<StackPanel Grid.Column="1">
<Button Content="Add Data" Click="Button_Click_1" Height="150"/>
<Button Content="Print" Click="Button_Click" Height="150"/>
</StackPanel>
</Grid>
</Window>
public partial class MainWindow : Window
{
public PlotModel MyModel { get; private set; }
public MainWindow()
{
MyModel = new PlotModel { Title = "Example 1" };
MyModel.Series.Add(new FunctionSeries(Math.Cos, 0, 10, 0.1, "cos(x)"));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Visual visual = ReportGrid as Visual;
Print(visual);
}
private void Print(Visual v)
{
System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement;
if (e == null)
return;
PrintDialog pd = new PrintDialog();
pd.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;
if (pd.ShowDialog() == true)
{
//store original scale
Transform originalScale = e.LayoutTransform;
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
e.ActualHeight);
//Transform the Visual to scale
e.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
e.Measure(sz);
e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
pd.PrintVisual(v, "My Print");
//apply the original transform.
e.LayoutTransform = originalScale;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
plot.Model = MyModel;
}
}
我做了很多测试。事实证明打印问题与 Oxyplot 2.1.2 版本有关。当我使用 2.0 版本的库时,.NET Framework 4.8 和 .NET7 的打印工作正常。很抱歉我原来的帖子造成了混乱。 我希望此信息可以帮助也遇到此问题的人。