Capture Image in WPF
and print the captured image:
In the
previous article we have learned how to print WPF visual and fit into the
printing page. Now you would learn how to capture the image in WPF and
print that image to the printer in a page fit.
Steps to capture the image and
print:
- Add Reference the
ReachFramework.dll.
- Add reference of the
System.Printing.dll.
- Get the capabilities of the
selected printer.
- Calculate the scaling of the
printer with wrt to visual to be printed.
- Capture the image of the
visual Element.
- Create the new visual.
- Create the Drawing context
from the new visual.
- Render the image to the
drawing context.
- Close the drawing context,
now visual contain the image captured.
- Print the new visual.
Code in the
btnPrintCaptureImage_OnClick handler.
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);
//get the size of the printer page
Size sz = new Size(capabilities.PageImageableArea.ExtentWidth,
capabilities.PageImageableArea.ExtentHeight);
//Capture the image of the visual in the same size as
Printing page.
RenderTargetBitmap bmp = new
RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bmp.Render(this);
//create
new visual which would be initialized by image
DrawingVisual
vis = new DrawingVisual();
//create a
drawing context so that image can be rendered to print
DrawingContext
dc = vis.RenderOpen();
dc.DrawImage(bmp,new System.Windows.Rect(sz));
dc.Close();
//now print
the image visual to printer to fit on the one page.
printDlg.PrintVisual(vis, "Image Fit to Page WPF Print");
}
Summary: Now, we have idea how to capture
image and print that captured image in WPF.