Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C#

Printing the .NET TreeView Control

Rate me:
Please Sign up or sign in to vote.
4.41/5 (29 votes)
14 Oct 2013Apache2 min read 211.9K   2.6K   56   54
A class to handle printing a .NET TreeView control.

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.

C#
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;
    }
    //keep track of the original tree settings
    int tempHeight = tree.Height;
    int tempWidth = tree.Width;
    BorderStyle tempBorder = tree.BorderStyle;
    bool tempScrollable = tree.Scrollable;
    TreeNode selectedNode = tree.SelectedNode;
    //setup the tree to take the snapshot
    tree.SelectedNode = null;
    DockStyle tempDock = tree.Dock;
    tree.Height = height + _scrollBarHeight;
    tree.Width = width + _scrollBarWidth;
    tree.BorderStyle = BorderStyle.None;
    tree.Dock = DockStyle.None;
    //get the image of the tree
    this._controlImage = GetImage(tree.Handle, tree.Width, tree.Height);
    //reset the tree to its original settings
    tree.BorderStyle = tempBorder;
    tree.Width = tempWidth;
    tree.Height = tempHeight;
    tree.Dock = tempDock;
    tree.Scrollable = tempScrollable;
    tree.SelectedNode = selectedNode;
    //give the window time to update
    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.

C#
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);
    //check to see if we need more pages
    if((this._controlImage.Height - this._scrollBarHeight) > sourceRect.Bottom
     || (this._controlImage.Width - this._scrollBarWidth) > sourceRect.Right){
        //need more pages
        e.HasMorePages = true;
    }
    if(this._currentDir == PrintDirection.Horizontal){
        if(sourceRect.Right < (this._controlImage.Width - this._scrollBarWidth)){
            //still need to print horizontally
            _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);
    }

    //print footer
    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);
        
    //print header
    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! 

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPrint Preview Scrollbar Pin
Boiledham10-Feb-14 9:39
Boiledham10-Feb-14 9:39 
QuestionAn unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Pin
nicewave22-Jan-14 13:31
nicewave22-Jan-14 13:31 
AnswerRe: An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Pin
GarthJones26-Jul-18 1:53
GarthJones26-Jul-18 1:53 
QuestionWell done sir! Pin
CJV_Xtream15-Oct-13 6:44
CJV_Xtream15-Oct-13 6:44 
AnswerRe: Well done sir! Pin
Mark Pitman15-Oct-13 7:02
Mark Pitman15-Oct-13 7:02 
QuestionDoes not work (error) Pin
C4RL.07-Oct-13 1:51
C4RL.07-Oct-13 1:51 
AnswerRe: Does not work (error) Pin
GarthJones26-Jul-18 1:54
GarthJones26-Jul-18 1:54 
QuestionLicense Pin
Alan Hayslep29-Aug-13 0:38
Alan Hayslep29-Aug-13 0:38 
AnswerRe: License Pin
Mark Pitman2-Sep-13 12:52
Mark Pitman2-Sep-13 12:52 
GeneralRe: License Pin
Alan Hayslep2-Sep-13 22:33
Alan Hayslep2-Sep-13 22:33 
QuestionPrints black band in XP Pin
Dirkus Maximus30-Apr-12 20:00
Dirkus Maximus30-Apr-12 20:00 
QuestionGreat Class, but i fixed a little Bug for me Pin
Member 796001516-Dec-11 2:59
Member 796001516-Dec-11 2:59 
QuestionNice Work! Pin
byte2bits13-Aug-11 5:43
byte2bits13-Aug-11 5:43 
GeneralThanks for sharing Pin
Alexander Nowak7-Feb-11 0:06
Alexander Nowak7-Feb-11 0:06 
GeneralWorks perfectly Pin
Martin Wielandt29-Sep-10 3:39
Martin Wielandt29-Sep-10 3:39 
Generalsome errore in 2008 Pin
aidin_dotnet8-Jun-10 2:22
aidin_dotnet8-Jun-10 2:22 
GeneralGeneric error in GDI+ Pin
philanilom1-Mar-10 14:05
philanilom1-Mar-10 14:05 
GeneralPrintTreeView on VS 2008 Pin
andyinpedro24-Aug-09 17:31
andyinpedro24-Aug-09 17:31 
GeneralRe: PrintTreeView on VS 2008 Pin
Vivek Tewari21-Jan-13 4:01
Vivek Tewari21-Jan-13 4:01 
GeneralThank You Pin
kdpo19906-Jul-09 20:36
kdpo19906-Jul-09 20:36 
Generalbugfix - class PrintHelper - GetImage() Pin
fiftyfifty18-Dec-07 2:05
fiftyfifty18-Dec-07 2:05 
QuestionCrashing with Invalid Parameter Error Pin
Peter Maslin12-Dec-07 0:51
Peter Maslin12-Dec-07 0:51 
I get the same thing as above , has anyone found a solution for it ?
AnswerRe: Crashing with Invalid Parameter Error Pin
Carl Vaillancourt2-May-08 5:47
Carl Vaillancourt2-May-08 5:47 
GeneralRe: Crashing with Invalid Parameter Error Pin
Member 443883226-Sep-09 1:31
Member 443883226-Sep-09 1:31 
QuestionCrashing at image set Pin
AbhayAuto13-Sep-07 4:08
AbhayAuto13-Sep-07 4:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.