WPF打印画布以适合页面

时间:2016-12-05 13:53:59

标签: c# wpf canvas printing printdialog

我试图在PrintDialog的帮助下将画布打印到打印机和文件。我希望画布适合页面。我能够使用以下代码实现它

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;
    }
}

上面的代码似乎按预期工作,但是当我使用PDF编写器将其写入PDF文件时,当保存对话框显示时,画布将调整大小并将恢复正常。因此,UI中也会出现调整大小。

这个画布已经是一个克隆的画布,如果没有在UI中显示它就无法打印,因为有一些后台操作正在填充画布中的元素,这些元素只有在加载后才能启动。因此,克隆的画布显示为打印预览。

有没有人知道一个好的解决方案,或者可能改进现有解决方案以解决UI调整大小问题?

0 个答案:

没有答案