Appendix N
Printing and Graphics

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.

Windows Forms Printing

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.

Printing Steps

The following steps summarize how to print in a Windows Forms application.

  1. Create a PrintDocument object either at design time or at run time.
  2. Start the printing process by doing one of the following:
    1. To send a printout to a printer, call the PrintDocument object’s Print method.
    2. To display a print preview in a PrintPreviewDialog:
      1. Create a PrintPreviewDialog object either at design time or at run time.
      2. Set the object’s Document property equal to the PrintDocument object you created in Step 1.
      3. Call the dialog’s ShowDialog method to display it.
    3. To display a print preview in a PrintPreviewControl:
      1. Create a PrintPreviewControl object either at design time or at run time.
      2. Set the object’s Document property equal to the PrintDocument object you created in Step 1.
  3. Catch the 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.

Graphics Namespaces

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.

Drawing Graphics

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.

Graphics

The Graphics object represents a drawing surface. The following table lists the Graphics object’s drawing methods.

Drawing MethodPurpose
DrawArcDraws an arc of an ellipse
DrawBezierDraws a Bézier curve
DrawBeziersDraws a series of connected Bézier curves
DrawClosedCurveDraws a smooth closed curve that connects a series of points, joining the final point to the first point
DrawCurveDraws a smooth curve that connects a series of points
DrawEllipseDraws an ellipse
DrawIconDraws an Icon onto the Graphics object’s drawing surface
DrawIconUnstretchedDraws an Icon object onto the Graphics object’s drawing surface without scaling
DrawImageDraws an Image object onto the Graphics object’s drawing surface
DrawImageUnscaledDraws an Image object onto the drawing surface without scaling
DrawLineDraws a line
DrawLinesDraws a series of connected lines
DrawPathDraws a GraphicsPath object
DrawPieDraws a pie slice taken from an ellipse
DrawPolygonDraws a polygon
DrawRectangleDraws a rectangle
DrawRectanglesDraws a series of rectangles
DrawStringDraws text

The following table lists the Graphics object’s area filling methods.

Filling MethodPurpose
FillClosedCurveFills a smooth curve that connects a series of points
FillEllipseFills an ellipse
FillPathFills a GraphicsPath object
FillPieFills a pie slice taken from an ellipse
FillPolygonFills a polygon
FillRectangleFills a rectangle
FillRectanglesFills a series of rectangles
FillRegionFills a Region object

The following table lists other useful Graphics object properties and methods.

Properties and MethodsPurpose
AddMetafileCommentAdds a comment to a metafile
ClearClears the Graphics object and fills it with a specific color
ClipDetermines the Region object used to clip any drawing the program does on the Graphics surface
DisposeReleases the resources held by the Graphics object
DpiXReturns the horizontal number of dots per inch (DPI) for this object’s surface
DpiYReturns the vertical number of dots per inch (DPI) for this object’s surface
EnumerateMetafileInvokes a callback method for each record defined in a metafile
ExcludeClipUpdates the Graphics object’s clipping region to exclude the area defined by a Region or Rectangle
FromHdcCreates a new Graphics object from a device context handle (hDC)
FromHwndCreates a new Graphics object from a window handle (hWnd)
FromImageCreates a new Graphics object to draw on an Image object
InterpolationModeControls anti-aliasing when drawing scaled images to determine how smooth the result is
IntersectClipUpdates the Graphics object’s clipping region to be the intersection of the current clipping region and the area defined by a Region or Rectangle
IsVisibleReturns true if a specified point is within the Graphics object’s visible clipping region
MeasureCharacterRangesReturns an array of Region objects that show where each character in a string will be drawn
MeasureStringReturns a SizeF structure that gives the size of a string drawn on the Graphics object with a particular font
MultiplyTransformMultiplies the Graphics object’s current transformation matrix by another transformation matrix
PageScaleDetermines the amount by which drawing commands are scaled
PageUnitDetermines 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)
RenderingOriginDetermines the point used as a reference when hatching
ResetClipResets the object’s clipping region so that the drawing is not clipped
ResetTransformationResets the object’s transformation matrix to the identity matrix
RestoreRestores the Graphics object to a state saved by the Save method
RotateTransformAdds a rotation to the object’s current transformation
SaveSaves the object’s current state
ScaleTransformAdds a scaling transformation to the Graphics object’s current transformation
SetClipSets or merges the Graphics object’s clipping area to another Graphics object, a GraphicsPath object, or a Rectangle
SmoothingModeControls anti-aliasing when drawing lines, curves, or filled areas
TextRenderingHintControls anti-aliasing and hinting when drawing text
TransformGets or sets the Graphics object’s transformation matrix
TransformPointsApplies the object’s current transformation to an array of points
TranslateTransformAdds a translation transformation to the Graphics object’s current transformation

Pen

The Pen object determines the appearance of drawn lines. The following table lists the Pen object’s most useful properties and methods.

Properties and MethodsPurpose
AlignmentDetermines whether the line is drawn inside or centered on the theoretical perfectly thin line specified by the drawing routine
BrushDetermines the Brush used to fill the line
ColorDetermines the line’s color
CompoundArrayLets you draw a line that is striped lengthwise
CustomEndCapDetermines the line’s end cap
CustomStartCapDetermines the line’s start cap
DashCapDetermines the cap drawn at the ends of dashes
DashOffsetDetermines the distance from the start of the line to the start of the first dash
DashPatternAn array of floats that specifies a custom dash pattern
DashStyleDetermines the line’s dash style
EndCapDetermines the cap used at the end of the line
LineJoinDetermines how lines are joined by a method that draws connected lines such as DrawPolygon
MultiplyTransformMultiplies the Pen object’s current transformation by another transformation matrix
ResetTransformResets the Pen object’s transformation to the identity transformation
RotateTransformAdds a rotation transformation to the Pen object’s current transformation
ScaleTransformAdds a scaling transformation to the Pen object’s current transformation
SetLineCapThis method takes parameters that let you specify the Pen object’s StartCap, EndCap, and LineJoin properties at the same time
StartCapDetermines the cap used at the start of the line
TransformDetermines the transformation applied to the initially circular “pen tip” used to draw lines
WidthThe width of the pen

Brushes

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.

ClassPurpose
SolidBrushFills areas with a single solid color
TextureBrushFills areas with a repeating image
HatchBrushFills areas with a repeating hatch pattern
LinearGradientBrushFills areas with a linear gradient of two or more colors
PathGradientBrushFills areas with a color gradient that follows a path

GraphicsPath

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 MethodsPurpose
CloseAllFiguresCloses all open figures by connecting their last points with their first points and then starts a new figure.
CloseFigureCloses the current figure by connecting its last point with its first point and then starts a new figure.
FillModeDetermines how the path handles overlaps when you fill it. This property can take the values Alternate and Winding.
FlattenConverts any curves in the path into sequences of lines.
GetBoundsReturns a RectangleF structure representing the path’s bounding box.
GetLastPointReturns the last PointF structure in the PathPoints array.
IsOutlineVisibleReturns true if the indicated point lies beneath the path’s outline.
IsVisibleReturns true if the indicated point lies in the path’s interior.
PathDataReturns a PathData object that encapsulates the path’s graphical data.
PathPointsReturns an array of PointF structures giving the points in the path.
PathTypesReturns an array of bytes representing the types of the points in the path.
PointCountReturns the number of points in the path.
ResetClears the path data and resets FillMode to Alternate.
ReverseReverses the order of the path’s data.
StartFigureStarts a new figure, so future data is added to the new figure.
TransformApplies a transformation matrix to the path.
WarpApplies a warping transformation defined by mapping a parallelogram onto a rectangle to the path.
WidenEnlarges the curves in the path to enclose a line drawn by a specific pen.

StringFormat

The StringFormat object determines how text is formatted. The following table lists the StringFormat object’s most useful properties and methods.

Properties and MethodsPurpose
AlignmentDetermines the text’s horizontal alignment. This can be Near (left), Center (middle), or Far (right).
FormatFlagsGets or sets flags that modify the StringFormat object’s behavior.
GetTabStopsReturns an array of floats giving the positions of tab stops.
HotkeyPrefixDetermines how the hotkey prefix character is displayed. This can be Show, Hide, or None.
LineAlignmentDetermines the text’s vertical alignment. This can be Near (top), Center (middle), or Far (bottom).
SetMeasureableCharacterRangesSets an array of CharacterRange structures representing ranges of characters that will later be measured by the Graphics object’s MeasureCharacterRanges method.
SetTabStopsSets an array of floats giving the positions of tab stops.
TrimmingDetermines how the text is trimmed if it cannot fit within a layout rectangle.

Image

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 MethodsPurpose
DisposeFrees the resources associated with this image
FlagsReturns attribute flags for the image
FromFileLoads an image from a file
FromHbitmapLoads a Bitmap image from a Windows bitmap handle
FromStreamLoads an image from a data stream
GetBoundsReturns a RectangleF structure representing the rectangle’s bounds
GetPixelFormatSizeReturns the color resolution (bits per pixel) for a specified PixelFormat
GetThumbnailImageReturns a thumbnail representation of the image
HeightReturns the image’s height
HorizontalResolutionReturns the horizontal resolution of the image in pixels per inch
IsAlphaPixelFormatReturns true if the specified PixelFormat contains alpha (opaqueness) information
PaletteDetermines the ColorPalette object used by the image
PhysicalDimensionReturns a SizeF structure giving the image’s dimensions in pixels for Bitmaps and 0.01 millimeters for Metafiles
PixelFormatReturns the image’s pixel format
RawFormatReturns an ImageFormat object representing the image’s raw format
RotateFlipRotates, flips, or rotates and flips the image
SaveSaves the image in a file or stream with a given data format
SizeReturns a Size structure containing the image’s width and height in pixels
VerticalResolutionReturns the vertical resolution of the image in pixels per inch
WidthReturns the image’s width

Bitmap

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.

MethodPurpose
FromHiconLoads a Bitmap image from a Windows icon handle
FromResourceLoads a Bitmap image from a Windows resource
GetPixelReturns a Color representing a specified pixel
LockBitsLocks the Bitmap image’s data in memory, so it cannot move until the program calls UnlockBits
MakeTransparentMakes all pixels with a specified color transparent by setting the alpha component of those pixels to 0
SetPixelSets a specified pixel’s Color value
SetResolutionSets the Bitmap image’s horizontal and vertical resolution in dots per inch (DPI)
UnlockBitsUnlocks the Bitmap image’s data in memory so that the system can relocate it, if necessary

Metafile

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.

MethodPurpose
GetMetafileHeaderReturns the MetafileHeader object associated with this Metafile.
PlayRecordPlays a metafile record. Use the Graphics class’s EnumerateMetafile method to get the data needed to play metafile records.

WPF Printing

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.

Using a Paginator

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 generated
  • PageCount—Returns the number of pages that have been formatted
  • PageSize—Gets or sets the suggested size of the printed page
  • Source—Returns the element being paginated

Creating Documents

The 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.

FlowDocuments

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.

FixedDocuments

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>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset