pankaj
pankaj

Reputation: 207

How to take the print of wpf user control using c#?

I have one user control in which i displayed the map and the data in the datagrid.

I have tried following code but it does not works.

        PrintDialog printDialog = new PrintDialog();

        // if user clicks on cancel button of print dialog box then no need to print the map control
        if (!(bool)printDialog.ShowDialog())
        {
            return;
        }
        else // this means that user click on the print button
        {
            // do nothing
        }

        this.Measure(new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));
        this.Arrange(new Rect(new Point(20, 20), new Size(this.ActualWidth, this.ActualHeight)));

        // print the map control
        printDialog.PrintVisual(this, "Karte drucken");

Issue : When data grid has large number of records then user control gets scroll bar, but after printing the user control, only visible part of user control is printed and not the data present which we can see after scrolling down.I want to print whole content of user control.

Is there any solution for this, also how can we see print preview in wpf ?

Upvotes: 1

Views: 3714

Answers (1)

Swapnil Vishwakarma
Swapnil Vishwakarma

Reputation: 25

Please check the following link, it should be helpful. Print Preview WPF

Code

 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(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 Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));

   //now print the visual to printer to fit on the one page.
   printDlg.PrintVisual(this, "First Fit to Page WPF Print");

}

Upvotes: 2

Related Questions