Visual Studio 2012 C# PrintPreviewControl

Posted on Monday, May 13, 2013

I have a need to print
out some documents programmatically using .Net and C#.

This document just goes
over the PrintPreviewControl

Set up a Virtual Printer

Before I starting
writing this program I downloaded and installed a virtual printer. In the past I have used a CUPS printer on my
Mac but for this time around I looked around for something to run directly on
my Windows 7 machine. I found CutePDF at
http://www.cutepdf.com/Products/CutePDF/writer.asp [1]

I installed this virtual
server so I could test my printing without using up so much paper.

Create a basic Windows Form Application

From Visual Studio 2012
Professional click on New project (or from the menu select File --> New --> Project

1.Select Windows Forms Application

2.I named mine PrintPreviewTestApp

3.Click OK

In the Toolbox search
for "print" the PrintDocument
and PrintPreviewControl will be displayed

Drag the PrintDocument
and PrintPreivewControl on the the Form.

Double click on the
PrintDocument1

This will open the
PrintPageEventArgs method for this document

Here is the code I wrote for the document creation

privatevoid printDocument1_PrintPage(object sender,

Font font = newFont("Microsoft
Sans Serif", 48F,

System.Drawing.FontStyle.Bold,

System.Drawing.GraphicsUnit.Point,

((byte)(0)));

Graphics g = e.Graphics;

g.DrawString("Print
Me",
font,

System.Drawing.Brushes.Black, 100, 50);

}

Select the PrintPreviewControl
and resize it slightly

From the PrintPreviewControl
properties set the Document Property to the printDocument1

Run the program by
clicking start

The program shows the
print preview for this document.

Add a "Print"
button to the form

privatevoid button1_Click(object sender, EventArgs e) {

this.printDocument1.Print();

}

Here is the code to
print the document.

Run the program and
click Print

Add two new buttons,
Zoom and Shrink to Fit

privatevoid button2_Click(object sender, EventArgs e) {

printPreviewControl1.Zoom = 1.0;

}

privatevoid button3_Click(object sender, EventArgs e) {

printPreviewControl1.AutoZoom = true;

}

Here is the code for the
buttons. The first zooms to 100% and the
second shrinks to fit

Run the program

Click on the Zoom
button, the document is set to 100% and you can scroll around it.