Introduction
I looked and looked for a sample code to print TreeView
controls in C#. I couldn't find anything that did exactly what I needed, so I broke down and wrote it myself!
Background
During my search for a printing sample, I came across this article by Koay Kah Hoe, which presents a solution in C++. It gave me a few ideas and after finding some information on Usenet about getting an image of a control, I was ready to code.
Using the code
In order to print the entire TreeView
, the size of the area of all visible nodes has to be calculated and then the tree must be resized to accommodate the contents. This is all handled in the PrepareTreeImage
method of the PrintUtility
class.
private void PrepareTreeImage(TreeView tree){
_scrollBarWidth = tree.Width - tree.ClientSize.Width;
_scrollBarHeight = tree.Height - tree.ClientSize.Height;
tree.Nodes[0].EnsureVisible();
int height = tree.Nodes[0].Bounds.Height;
this._nodeHeight = height;
int width = tree.Nodes[0].Bounds.Right;
TreeNode node = tree.Nodes[0].NextVisibleNode;
while(node != null){
height += node.Bounds.Height;
if(node.Bounds.Right > width){
width = node.Bounds.Right;
}
node = node.NextVisibleNode;
}
int tempHeight = tree.Height;
int tempWidth = tree.Width;
BorderStyle tempBorder = tree.BorderStyle;
bool tempScrollable = tree.Scrollable;
TreeNode selectedNode = tree.SelectedNode;
tree.SelectedNode = null;
DockStyle tempDock = tree.Dock;
tree.Height = height + _scrollBarHeight;
tree.Width = width + _scrollBarWidth;
tree.BorderStyle = BorderStyle.None;
tree.Dock = DockStyle.None;
this._controlImage = GetImage(tree.Handle, tree.Width, tree.Height);
tree.BorderStyle = tempBorder;
tree.Width = tempWidth;
tree.Height = tempHeight;
tree.Dock = tempDock;
tree.Scrollable = tempScrollable;
tree.SelectedNode = selectedNode;
Application.DoEvents();
}
When it is time to print the resulting image, there is some calculation to do to divide the image up into sections of the proper size to fit on the printed page. This is handled in the printDoc_PrintPage
method which handles the PrintPage
event of the PrintDocument
. This is pretty straightforward. We have to keep track of the direction we are moving in, horizontally or vertically, across the source image. We also must keep track of where we left off in the image when the previous page was printed.
private void printDoc_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e) {
this._pageNumber++;
Graphics g = e.Graphics;
Rectangle sourceRect = new Rectangle(_lastPrintPosition, e.MarginBounds.Size);
Rectangle destRect = e.MarginBounds;
if((sourceRect.Height % this._nodeHeight) > 0){
sourceRect.Height -= (sourceRect.Height % this._nodeHeight);
}
g.DrawImage(this._controlImage, destRect, sourceRect, GraphicsUnit.Pixel);
if((this._controlImage.Height - this._scrollBarHeight) > sourceRect.Bottom
|| (this._controlImage.Width - this._scrollBarWidth) > sourceRect.Right){
e.HasMorePages = true;
}
if(this._currentDir == PrintDirection.Horizontal){
if(sourceRect.Right < (this._controlImage.Width - this._scrollBarWidth)){
_lastPrintPosition.X += (sourceRect.Width + 1);
}
else{
_lastPrintPosition.X = 0;
_lastPrintPosition.Y += (sourceRect.Height + 1);
this._currentDir = PrintDirection.Vertical;
}
}
else if(this._currentDir == PrintDirection.Vertical && sourceRect.Right
< (this._controlImage.Width - this._scrollBarWidth)){
this._currentDir = PrintDirection.Horizontal;
_lastPrintPosition.X += (sourceRect.Width + 1);
}
else{
_lastPrintPosition.Y += (sourceRect.Height + 1);
}
Brush brush = new SolidBrush(Color.Black);
string footer = this._pageNumber.ToString(
System.Globalization.NumberFormatInfo.CurrentInfo);
Font f = new Font(FontFamily.GenericSansSerif, 10f);
SizeF footerSize = g.MeasureString(footer, f);
PointF pageBottomCenter = new PointF(e.PageBounds.Width/2,
e.MarginBounds.Bottom +
((e.PageBounds.Bottom - e.MarginBounds.Bottom)/2));
PointF footerLocation = new PointF(pageBottomCenter.X - (footerSize.Width/2),
pageBottomCenter.Y - (footerSize.Height/2));
g.DrawString(footer, f, brush, footerLocation);
if(this._pageNumber == 1 && this._title.Length > 0){
Font headerFont = new Font(FontFamily.GenericSansSerif, 24f,
FontStyle.Bold, GraphicsUnit.Point);
SizeF headerSize = g.MeasureString(this._title, headerFont);
PointF headerLocation = new PointF(e.MarginBounds.Left,
((e.MarginBounds.Top - e.PageBounds.Top)/2) - (headerSize.Height/2));
g.DrawString(this._title, headerFont, brush, headerLocation);
}
}
The PrintUtility
class should be fairly easy to use from just about any Windows Forms application. Just call either PrintTree
or PrintPreviewTree
, passing in your TreeView
.
When I first decided to tackle the problem of printing the TreeView
, I thought it was going to take quite a bit of time and code. I was really surprised once I figured out the algorithm, how simple it really is.
I will also be posting this article and code on my blog.
Update
The code is now available on GitHub. If you have changes you'd like to see incorporated, fork the code and send a pull request!