我搜索了如何打印WPF控件的选项,并找到了一些解决方案。我确实需要在保持高宽比的同时使我的打印控件适合打印页面(我的控件是正方形;数独网格)。
我找到了一种解决方案,可以调整控件的大小和位置以适合页面。效果很好,但它也将控件重新定位在我的窗口上。
这是我用于打印和缩放的代码:
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = dialog.PrintQueue.GetPrintCapabilities(dialog.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / mrizka.ActualWidth, capabilities.PageImageableArea.ExtentHeight / mrizka.ActualHeight);
//Transform the Visual to scale
mrizka.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
mrizka.Measure(sz);
mrizka.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
dialog.PrintVisual(mrizka, mrizka.getID().ToString());
我尝试了两种方法来解决这个问题:
没有工作,由于某种原因我以异常结束:提供的DependencyObject不是此Freezable的上下文,但是奇怪的是仅在某些情况下。
请问我有什么想法<谢谢。
最佳答案
我知道这个问题已经很老了,但我自己正在寻找解决方案。这是我当前正在使用的解决方案。我将原始转换存储在framework元素中,然后在打印完成后重新应用它。
private void Print(Visual v)
{
System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement ;
if (e == null)
return;
PrintDialog pd = new PrintDialog();
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;
}
}
关于.net - WPF打印以适合页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931961/