缩放WPF窗口以进行打印

时间:2018-03-15 01:34:49

标签: c# wpf visual-studio-2017

晚安,

我正在开发VS2017中使用c#的小型WPF应用程序。它基本上只是为我在该领域的工人进行计算。我已经构建并测试了所有内容,但是,在打印结果时,我遇到了一个问题。我已经浏览了互联网的角落,并且已经打开打印对话框甚至打印到PDF。我遇到的问题是,当它打印时,它是全面的。我只需要能够将应用程序窗口缩放到其大小的80-90%然后打印。我将添加代码,看看我是否只是忽略了一些东西。

    private void InvokePrint(object sender, RoutedEventArgs e)
    {
        PrintDialog printDlg = new System.Windows.Controls.PrintDialog();

        if (printDlg.ShowDialog() == true)

        {

            //get selected printer capabilities

            System.Printing.PrintCapabilities capabilities = printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);



            //get scale of the print wrt to screen of WPF visual

            double scale = Math.Min((ActualWidth*.9),ActualHeight);



            //get the size of the printer page

            Size sz = new Size((Width*.9), ActualHeight);



            //update the layout of the visual to the printer page size.

            this.Measure(sz);

            this.Arrange(new Rect(new Point(0,0), sz));



            //now print the visual to printer to fit on the one page.

            printDlg.PrintVisual(this, "Offset Calculations");

What it is printing

What I want to print

1 个答案:

答案 0 :(得分:0)

添加对ReachFramework.dll 4.0的引用

        PrintDialog dlg = new PrintDialog();
        if ((bool)dlg.ShowDialog().GetValueOrDefault()) {
            //switch landscape
            dlg.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;

            //get selected printer capabilities
            System.Printing.PrintCapabilities capabilities = dlg.PrintQueue.GetPrintCapabilities(dlg.PrintTicket);

            //get scale of the print wrt to screen of WPF visual
            double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /  this.ActualHeight);

            //Transform the Visual to scale
            this.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.
            this.Measure(sz);
            this.Arrange(new Rect(new System.Windows.Point((int)capabilities.PageImageableArea.OriginWidth, (int)capabilities.PageImageableArea.OriginHeight), sz));

            //show the print dialog
            dlg.PrintVisual(this, "MyDoc_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));
        }