3

I am trying to print a canvas to both printer and file with the help of PrintDialog. I want the canvas to fit the page. I was able to achieve it using the following code

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

The above code seems to be working as expected but when I am writing it to a PDF file using a PDF writer, the canvas will be resized when the save dialog box shows up and it will be set back to normal. So there is a resizing happening in the UI as well.

This canvas is already a cloned one and this cannot be printed without showing it in the UI because there are some background operations happening to fill the elements in the canvas which can be started only after it's loaded. Hence the cloned canvas is shown as a print preview.

Does anyone know of a good solution, or perhaps improve on the existing one to solve the UI resizing issue?

Subru
  • 343
  • 2
  • 13

0 Answers0