Click here to Skip to main content
11,934,425 members (40,161 online)
Click here to Skip to main content
Add your own
alternative version


51 bookmarked

Printing the .NET TreeView Control

, 14 Oct 2013 Apache
Rate this:
Please Sign up or sign in to vote.
A class to handle printing a .NET TreeView control.


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!


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;
    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

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) {
    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);
            _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);
        _lastPrintPosition.Y += (sourceRect.Height + 1);

    //print footer
    Brush brush = new SolidBrush(Color.Black);
    string footer = this._pageNumber.ToString(
    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.


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! 


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


About the Author

Mark Pitman
Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionPrint Preview Scrollbar Pin
Boiledham10-Feb-14 10:39
memberBoiledham10-Feb-14 10:39 
QuestionAn unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Pin
nicewave22-Jan-14 14:31
membernicewave22-Jan-14 14:31 
QuestionWell done sir! Pin
CJV_Xtream15-Oct-13 7:44
memberCJV_Xtream15-Oct-13 7:44 
AnswerRe: Well done sir! Pin
Mark Pitman15-Oct-13 8:02
memberMark Pitman15-Oct-13 8:02 
QuestionDoes not work (error) Pin
C4RL.07-Oct-13 2:51
memberC4RL.07-Oct-13 2:51 
QuestionLicense Pin
Alan Hayslep29-Aug-13 1:38
memberAlan Hayslep29-Aug-13 1:38 
AnswerRe: License Pin
Mark Pitman2-Sep-13 13:52
memberMark Pitman2-Sep-13 13:52 
GeneralRe: License Pin
Alan Hayslep2-Sep-13 23:33
memberAlan Hayslep2-Sep-13 23:33 
QuestionPrints black band in XP Pin
Dirkus Maximus30-Apr-12 21:00
memberDirkus Maximus30-Apr-12 21:00 
QuestionGreat Class, but i fixed a little Bug for me Pin
Member 796001516-Dec-11 3:59
memberMember 796001516-Dec-11 3:59 
QuestionNice Work! Pin
byte2bits13-Aug-11 6:43
memberbyte2bits13-Aug-11 6:43 
GeneralThanks for sharing Pin
Alexander Nowak7-Feb-11 1:06
memberAlexander Nowak7-Feb-11 1:06 
GeneralWorks perfectly Pin
Martin Wielandt29-Sep-10 4:39
memberMartin Wielandt29-Sep-10 4:39 
Generalsome errore in 2008 Pin
aidin_dotnet8-Jun-10 3:22
memberaidin_dotnet8-Jun-10 3:22 
GeneralGeneric error in GDI+ Pin
philanilom1-Mar-10 15:05
memberphilanilom1-Mar-10 15:05 
GeneralPrintTreeView on VS 2008 Pin
andyinpedro24-Aug-09 18:31
memberandyinpedro24-Aug-09 18:31 
GeneralRe: PrintTreeView on VS 2008 Pin
vivek.tewari2421-Jan-13 5:01
membervivek.tewari2421-Jan-13 5:01 
GeneralThank You Pin
kdpo19906-Jul-09 21:36
memberkdpo19906-Jul-09 21:36 
Generalbugfix - class PrintHelper - GetImage() Pin
fiftyfifty18-Dec-07 3:05
memberfiftyfifty18-Dec-07 3:05 
QuestionCrashing with Invalid Parameter Error Pin
Peter Maslin12-Dec-07 1:51
memberPeter Maslin12-Dec-07 1:51 
AnswerRe: Crashing with Invalid Parameter Error Pin
Carl Vaillancourt2-May-08 6:47
memberCarl Vaillancourt2-May-08 6:47 
GeneralRe: Crashing with Invalid Parameter Error Pin
Member 443883226-Sep-09 2:31
memberMember 443883226-Sep-09 2:31 
QuestionCrashing at image set Pin
AbhayAuto13-Sep-07 5:08
memberAbhayAuto13-Sep-07 5:08 
Generalexcellent work, but a curious thing is happening Pin
NETtune7-Sep-07 0:00
memberNETtune7-Sep-07 0:00 
GeneralWithout images Pin
welo_200026-Jun-07 3:27
memberwelo_200026-Jun-07 3:27 
GeneralWorked great...Thanks. Pin
Tom Muras8-Jun-07 5:13
memberTom Muras8-Jun-07 5:13 
Generalprinting error after print preview Pin
Wimpie Ratte14-Feb-07 22:45
memberWimpie Ratte14-Feb-07 22:45 
Generalinfinite loop problem? [modified] Pin
Wimpie Ratte5-Feb-07 2:57
memberWimpie Ratte5-Feb-07 2:57 
GeneralRe: infinite loop problem? Pin
Mark Pitman5-Feb-07 7:20
memberMark Pitman5-Feb-07 7:20 
GeneralRe: infinite loop problem? [modified] Pin
Wimpie Ratte5-Feb-07 22:23
memberWimpie Ratte5-Feb-07 22:23 
GeneralRe: infinite loop problem? Pin
Wimpie Ratte15-Feb-07 0:36
memberWimpie Ratte15-Feb-07 0:36 
GeneralThanks! Pin
dino martino29-Jan-07 9:38
memberdino martino29-Jan-07 9:38 
GeneralTo late for me Pin
Alexandru Lungu25-Jan-07 12:59
memberAlexandru Lungu25-Jan-07 12:59 
GeneralUpdate Pin
Mark Pitman24-Jan-07 21:24
memberMark Pitman24-Jan-07 21:24 
GeneralSmall problem Pin
RO2521-Jan-07 9:43
memberRO2521-Jan-07 9:43 
GeneralRe: Small problem Pin
Mark Pitman24-Jan-07 21:27
memberMark Pitman24-Jan-07 21:27 
GeneralGot an error on PInvoke Pin
samiam10299-Jan-07 11:38
membersamiam10299-Jan-07 11:38 
GeneralRe: Got an error on PInvoke Pin
Mark Pitman24-Jan-07 21:27
memberMark Pitman24-Jan-07 21:27 
GeneralExcellent Pin
Belarussian13-Sep-06 21:01
memberBelarussian13-Sep-06 21:01 
GeneralGreat! Pin
jpichler30-Jun-06 4:54
memberjpichler30-Jun-06 4:54 
GeneralVS.NET 2005 Issue Pin
JGIS6-Mar-06 4:46
memberJGIS6-Mar-06 4:46 
GeneralRe: VS.NET 2005 Issue Pin
Nick A Carter13-Mar-06 4:40
memberNick A Carter13-Mar-06 4:40 
GeneralRe: VS.NET 2005 Issue Pin
Mark Pitman24-Jan-07 21:29
memberMark Pitman24-Jan-07 21:29 
GeneralNot useful for large trees Pin
Orsol10-Nov-05 4:53
memberOrsol10-Nov-05 4:53 
GeneralUsefull code Pin
Lak2216-Aug-05 2:40
memberLak2216-Aug-05 2:40 
GeneralMemory Hungry Pin
djspirit2-Jun-05 1:32
memberdjspirit2-Jun-05 1:32 
GeneralRe: Memory Hungry Pin
Mark Pitman24-Jan-07 21:31
memberMark Pitman24-Jan-07 21:31 
Generalcomplete tree Pin
PrabhakarPV31-May-04 23:14
memberPrabhakarPV31-May-04 23:14 
GeneralRe: complete tree Pin
Mark Pitman2-Jun-04 9:20
memberMark Pitman2-Jun-04 9:20 
GeneralRe: complete tree Pin
Lak2216-Aug-05 2:41
memberLak2216-Aug-05 2:41 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 14 Oct 2013
Article Copyright 2004 by Mark Pitman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid