This appendix provides information about printing and the graphics classes used by Windows Forms applications. Printing is different in Windows Forms and WPF applications. The next sections explain how to print in a Windows Forms application. The sections after that explain how to print in a WPF application.
The following section explains the basic printing process in a Windows Forms application. The section after that summarizes graphics classes and methods used to print in that kind of application.
The following steps summarize how to print in a Windows Forms application.
PrintDocument
object either at design time or at run time.PrintDocument
object’s Print
method.PrintPreviewDialog
:
PrintPreviewDialog
object either at design time or at run time.Document
property equal to the PrintDocument
object you created in Step 1.ShowDialog
method to display it.PrintPreviewControl
:
PrintPreviewControl
object either at design time or at run time.Document
property equal to the PrintDocument
object you created in Step 1.PrintDocument
object’s events to generate the printout.The following list summarizes the events raised by the PrintDocument
object.
BeginPrint
—This event indicates that printing is about to begin. The program can use this event to prepare for printing.QueryPageSettings
—This event occurs when the PrintDocument
object is about to generate a new page. The program can use this event to make changes that are specific to the page it is about to print.PrintPage
—This event is raised to generate a page of output. The program catches this event and uses the e.Graphics
parameter to generate output. After it finishes printing the page, the program sets the value e.HasMorePages
to indicate whether there are more pages to print.EndPrint
—This event is raised when printing is finished. The program can use it to clean up any data structures or resources it used while printing.The PrintPage
event receives a parameter e
that includes several properties that are useful when printing. The following list summarizes those properties.
Cancel
—Set this to true
to cancel the printout.Graphics
—This is a Graphics
object that the program can use to produce graphics.HasMorePages
—Set this to true
or false
to indicate whether there are more pages to print after the current one.MarginBounds
—This indicates the page boundaries inside the page’s margins. Normally you should draw inside these bounds.PageBounds
—This indicates the page’s printable boundaries.PageSettings
—This gives the page settings such as the paper size, a value indicating whether the page is printing in landscape mode, and the printer’s resolution.The following list summarizes the most important graphics namespaces and their most useful classes, structures, and enumerated values.
System.Drawing
—This namespace defines the most important graphics objects including Bitmap
, Brush
, Color
, Font
, FontFamily
, Graphics
, Icon
, Image
, Metafile
, Pen
, Pens
, Point
, PointF
, Rectangle
, RectangleF
, Region
, Size
, SizeF
, and SolidBrush
.System.Drawing.Drawing2D
—This namespace contains classes for more advanced two-dimensional drawing and classes that refine more basic drawing classes. Classes and enumerations defined in this namespace include Blend
, ColorBlend
, DashCap
, DashStyle
, GraphicsPath
, HatchBrush
, HatchStyle
, LinearGradientBrush
, LineCap
, LineJoin
, Matrix
, and PathGradientBrush
.System.Drawing.Imaging
—This namespace contains classes that deal with more advanced bitmap graphics including ColorMap
, ColorPalette
, ImageFormat
, Metafile
, MetafileHeader
, MetaHeader
, and WmfPlaceableFileHeader
.System.Drawing.Printing
—This namespace contains objects used for printing and managing the printer’s characteristics including Margins
, PageSettings
, PaperSize
, PaperSource
, PrinterResolution
, and PrinterSettings
.System.Drawing.Text
—This namespace contains classes for working with installed fonts including FontCollection
, InstalledFontCollection
, and PrivateFontCollection
.The basic steps for drawing in C# are to obtain a Graphics
object and use its methods to draw shapes. Brush
classes determine how shapes are filled, and Pen
classes determine how lines are drawn.
The following sections describe the most useful properties and methods provided by key drawing classes.
The Graphics
object represents a drawing surface. The following table lists the Graphics
object’s drawing methods.
Drawing Method | Purpose |
DrawArc | Draws an arc of an ellipse |
DrawBezier | Draws a Bézier curve |
DrawBeziers | Draws a series of connected Bézier curves |
DrawClosedCurve | Draws a smooth closed curve that connects a series of points, joining the final point to the first point |
DrawCurve | Draws a smooth curve that connects a series of points |
DrawEllipse | Draws an ellipse |
DrawIcon | Draws an Icon onto the Graphics object’s drawing surface |
DrawIconUnstretched | Draws an Icon object onto the Graphics object’s drawing surface without scaling |
DrawImage | Draws an Image object onto the Graphics object’s drawing surface |
DrawImageUnscaled | Draws an Image object onto the drawing surface without scaling |
DrawLine | Draws a line |
DrawLines | Draws a series of connected lines |
DrawPath | Draws a GraphicsPath object |
DrawPie | Draws a pie slice taken from an ellipse |
DrawPolygon | Draws a polygon |
DrawRectangle | Draws a rectangle |
DrawRectangles | Draws a series of rectangles |
DrawString | Draws text |
The following table lists the Graphics
object’s area filling methods.
Filling Method | Purpose |
FillClosedCurve | Fills a smooth curve that connects a series of points |
FillEllipse | Fills an ellipse |
FillPath | Fills a GraphicsPath object |
FillPie | Fills a pie slice taken from an ellipse |
FillPolygon | Fills a polygon |
FillRectangle | Fills a rectangle |
FillRectangles | Fills a series of rectangles |
FillRegion | Fills a Region object |
The following table lists other useful Graphics
object properties and methods.
Properties and Methods | Purpose |
AddMetafileComment | Adds a comment to a metafile |
Clear | Clears the Graphics object and fills it with a specific color |
Clip | Determines the Region object used to clip any drawing the program does on the Graphics surface |
Dispose | Releases the resources held by the Graphics object |
DpiX | Returns the horizontal number of dots per inch (DPI) for this object’s surface |
DpiY | Returns the vertical number of dots per inch (DPI) for this object’s surface |
EnumerateMetafile | Invokes a callback method for each record defined in a metafile |
ExcludeClip | Updates the Graphics object’s clipping region to exclude the area defined by a Region or Rectangle |
FromHdc | Creates a new Graphics object from a device context handle (hDC) |
FromHwnd | Creates a new Graphics object from a window handle (hWnd) |
FromImage | Creates a new Graphics object to draw on an Image object |
InterpolationMode | Controls anti-aliasing when drawing scaled images to determine how smooth the result is |
IntersectClip | Updates the Graphics object’s clipping region to be the intersection of the current clipping region and the area defined by a Region or Rectangle |
IsVisible | Returns true if a specified point is within the Graphics object’s visible clipping region |
MeasureCharacterRanges | Returns an array of Region objects that show where each character in a string will be drawn |
MeasureString | Returns a SizeF structure that gives the size of a string drawn on the Graphics object with a particular font |
MultiplyTransform | Multiplies the Graphics object’s current transformation matrix by another transformation matrix |
PageScale | Determines the amount by which drawing commands are scaled |
PageUnit | Determines the units of measurement: Display (depends on the device, typically pixel for monitors and 1/100 inch for printers), Document (1/300 inch), Inch , Millimeter , Pixel , or Point (1/72 inch) |
RenderingOrigin | Determines the point used as a reference when hatching |
ResetClip | Resets the object’s clipping region so that the drawing is not clipped |
ResetTransformation | Resets the object’s transformation matrix to the identity matrix |
Restore | Restores the Graphics object to a state saved by the Save method |
RotateTransform | Adds a rotation to the object’s current transformation |
Save | Saves the object’s current state |
ScaleTransform | Adds a scaling transformation to the Graphics object’s current transformation |
SetClip | Sets or merges the Graphics object’s clipping area to another Graphics object, a GraphicsPath object, or a Rectangle |
SmoothingMode | Controls anti-aliasing when drawing lines, curves, or filled areas |
TextRenderingHint | Controls anti-aliasing and hinting when drawing text |
Transform | Gets or sets the Graphics object’s transformation matrix |
TransformPoints | Applies the object’s current transformation to an array of points |
TranslateTransform | Adds a translation transformation to the Graphics object’s current transformation |
The Pen
object determines the appearance of drawn lines. The following table lists the Pen
object’s most useful properties and methods.
Properties and Methods | Purpose |
Alignment | Determines whether the line is drawn inside or centered on the theoretical perfectly thin line specified by the drawing routine |
Brush | Determines the Brush used to fill the line |
Color | Determines the line’s color |
CompoundArray | Lets you draw a line that is striped lengthwise |
CustomEndCap | Determines the line’s end cap |
CustomStartCap | Determines the line’s start cap |
DashCap | Determines the cap drawn at the ends of dashes |
DashOffset | Determines the distance from the start of the line to the start of the first dash |
DashPattern | An array of float s that specifies a custom dash pattern |
DashStyle | Determines the line’s dash style |
EndCap | Determines the cap used at the end of the line |
LineJoin | Determines how lines are joined by a method that draws connected lines such as DrawPolygon |
MultiplyTransform | Multiplies the Pen object’s current transformation by another transformation matrix |
ResetTransform | Resets the Pen object’s transformation to the identity transformation |
RotateTransform | Adds a rotation transformation to the Pen object’s current transformation |
ScaleTransform | Adds a scaling transformation to the Pen object’s current transformation |
SetLineCap | This method takes parameters that let you specify the Pen object’s StartCap , EndCap , and LineJoin properties at the same time |
StartCap | Determines the cap used at the start of the line |
Transform | Determines the transformation applied to the initially circular “pen tip” used to draw lines |
Width | The width of the pen |
The Brush
class is an abstract class, so you cannot make instances of it. Instead, you must make instances of one of its derived classes. The following table briefly describes these derived classes.
Class | Purpose |
SolidBrush | Fills areas with a single solid color |
TextureBrush | Fills areas with a repeating image |
HatchBrush | Fills areas with a repeating hatch pattern |
LinearGradientBrush | Fills areas with a linear gradient of two or more colors |
PathGradientBrush | Fills areas with a color gradient that follows a path |
The GraphicsPath
object represents a path defined by lines, curves, text, and other drawing commands. The following table lists the GraphicsPath
object’s most useful properties and methods.
Properties and Methods | Purpose |
CloseAllFigures | Closes all open figures by connecting their last points with their first points and then starts a new figure. |
CloseFigure | Closes the current figure by connecting its last point with its first point and then starts a new figure. |
FillMode | Determines how the path handles overlaps when you fill it. This property can take the values Alternate and Winding . |
Flatten | Converts any curves in the path into sequences of lines. |
GetBounds | Returns a RectangleF structure representing the path’s bounding box. |
GetLastPoint | Returns the last PointF structure in the PathPoints array. |
IsOutlineVisible | Returns true if the indicated point lies beneath the path’s outline. |
IsVisible | Returns true if the indicated point lies in the path’s interior. |
PathData | Returns a PathData object that encapsulates the path’s graphical data. |
PathPoints | Returns an array of PointF structures giving the points in the path. |
PathTypes | Returns an array of byte s representing the types of the points in the path. |
PointCount | Returns the number of points in the path. |
Reset | Clears the path data and resets FillMode to Alternate . |
Reverse | Reverses the order of the path’s data. |
StartFigure | Starts a new figure, so future data is added to the new figure. |
Transform | Applies a transformation matrix to the path. |
Warp | Applies a warping transformation defined by mapping a parallelogram onto a rectangle to the path. |
Widen | Enlarges the curves in the path to enclose a line drawn by a specific pen. |
The StringFormat
object determines how text is formatted. The following table lists the StringFormat
object’s most useful properties and methods.
Properties and Methods | Purpose |
Alignment | Determines the text’s horizontal alignment. This can be Near (left), Center (middle), or Far (right). |
FormatFlags | Gets or sets flags that modify the StringFormat object’s behavior. |
GetTabStops | Returns an array of float s giving the positions of tab stops. |
HotkeyPrefix | Determines how the hotkey prefix character is displayed. This can be Show , Hide , or None . |
LineAlignment | Determines the text’s vertical alignment. This can be Near (top), Center (middle), or Far (bottom). |
SetMeasureableCharacterRanges | Sets an array of CharacterRange structures representing ranges of characters that will later be measured by the Graphics object’s MeasureCharacterRanges method. |
SetTabStops | Sets an array of float s giving the positions of tab stops. |
Trimming | Determines how the text is trimmed if it cannot fit within a layout rectangle. |
The Image
class represents the underlying physical drawing surface hidden below the logical layer created by the Graphics
class. The Image
is abstract, so you cannot directly instantiate it. Instead, you must instantiate its child classes Bitmap
and Metafile
. The following table describes the Image
class’s most useful properties and methods, which are inherited by the Bitmap
and Metafile
classes.
Properties and Methods | Purpose |
Dispose | Frees the resources associated with this image |
Flags | Returns attribute flags for the image |
FromFile | Loads an image from a file |
FromHbitmap | Loads a Bitmap image from a Windows bitmap handle |
FromStream | Loads an image from a data stream |
GetBounds | Returns a RectangleF structure representing the rectangle’s bounds |
GetPixelFormatSize | Returns the color resolution (bits per pixel) for a specified PixelFormat |
GetThumbnailImage | Returns a thumbnail representation of the image |
Height | Returns the image’s height |
HorizontalResolution | Returns the horizontal resolution of the image in pixels per inch |
IsAlphaPixelFormat | Returns true if the specified PixelFormat contains alpha (opaqueness) information |
Palette | Determines the ColorPalette object used by the image |
PhysicalDimension | Returns a SizeF structure giving the image’s dimensions in pixels for Bitmap s and 0.01 millimeters for Metafile s |
PixelFormat | Returns the image’s pixel format |
RawFormat | Returns an ImageFormat object representing the image’s raw format |
RotateFlip | Rotates, flips, or rotates and flips the image |
Save | Saves the image in a file or stream with a given data format |
Size | Returns a Size structure containing the image’s width and height in pixels |
VerticalResolution | Returns the vertical resolution of the image in pixels per inch |
Width | Returns the image’s width |
The Bitmap
class represents an image defined by pixel data. The following table describes the class’s most useful methods that are not inherited from the Image
class.
Method | Purpose |
FromHicon | Loads a Bitmap image from a Windows icon handle |
FromResource | Loads a Bitmap image from a Windows resource |
GetPixel | Returns a Color representing a specified pixel |
LockBits | Locks the Bitmap image’s data in memory, so it cannot move until the program calls UnlockBits |
MakeTransparent | Makes all pixels with a specified color transparent by setting the alpha component of those pixels to 0 |
SetPixel | Sets a specified pixel’s Color value |
SetResolution | Sets the Bitmap image’s horizontal and vertical resolution in dots per inch (DPI) |
UnlockBits | Unlocks the Bitmap image’s data in memory so that the system can relocate it, if necessary |
The Metafile
class represents an image defined by metafile records. The following table describes the class’s most useful methods that are not inherited from the Image
class.
Method | Purpose |
GetMetafileHeader | Returns the MetafileHeader object associated with this Metafile . |
PlayRecord | Plays a metafile record. Use the Graphics class’s EnumerateMetafile method to get the data needed to play metafile records. |
To create a printout, a WPF application creates objects that represent lines, shapes, text, and whatever else needs to be printed. The program can scale those objects as necessary to fit the printout and the result takes advantage of the printer’s capabilities.
There are several ways a WPF application can produce printouts. The following sections describe two of the more useful: using a paginator and creating documents.
A paginator is an object that generates a printout’s pages. To create a printout by using a paginator, derive a new class from the DocumentPaginator
class. Override the GetPage
method to create the document’s pages. Also override the following properties.
IsPageCountValid
—Returns true
if all pages have been created. Returns false
if some pages have not yet been generatedPageCount
—Returns the number of pages that have been formattedPageSize
—Gets or sets the suggested size of the printed pageSource
—Returns the element being paginatedThe FlowDocument
and FixedDocument
classes allow you to arrange objects on a printout. The classes automatically arrange the objects appropriately. For example, they let you make text flow around other objects. The following sections describe these two document classes.
A FlowDocument
object holds other objects that represent graphical output such as text, images, and shapes. It arranges its objects to take best advantage of whatever space is available, much as a web browser rearranges its contents when it is resized.
The following code shows a short FlowDocument
.
<Window x:Class="WpfFlowDocument.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfFlowDocument" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0"
Content="Print" Click="printButton_Click"
Width="100" Height="30" VerticalAlignment="Top"/>
<FlowDocumentReader Grid.Row="1" VerticalAlignment="Top">
<FlowDocument Name="sampleFlowDocument">
<Paragraph FontSize="20" FontWeight="Bold">
Chapter 1. Lorem Ipsum
</Paragraph>
<Paragraph FontSize="16" FontWeight="Bold">
Dolor Sit Amet
</Paragraph>
<Paragraph>
<Floater HorizontalAlignment="Right">
<Paragraph>
<Grid Width="100" Height="100">
<Border BorderBrush="Black" BorderThickness="1"/>
<Polygon
Points="50,5 95,50 50,95 5,50"
Stroke="Black" StrokeThickness="5" />
</Grid>
</Paragraph>
</Floater>
Consectetur adipiscing elit ...
</Paragraph>
<Paragraph>
Nullam dapibus dapibus ...
</Paragraph>
<Paragraph>
Etiam lacus eros ...
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
</Grid>
</Window>
See the WPF documentation for information about the classes that you can use to produce output.
Like a FlowDocument
, a FixedDocument
holds graphical objects. Instead of rearranging its objects as space permits, a FixedDocument
always places its objects in the same positions. This is similar to the way a PostScript document displays items at fixed positions.
The following code shows XAML that defines a FixedDocument
inside a DocumentViewer
.
<DocumentViewer Grid.Row="1">
<FixedDocument Name="sampleFixedDocument">
<PageContent Width="850" Height="1100">
<FixedPage Width="850" Height="1100" Margin="100">
... Page 1 content elements ...
</FixedPage>
</PageContent>
<PageContent Width="850" Height="1100">
<FixedPage Width="850" Height="1100" Margin="100">
... Page 1 content elements ...
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>