Sent this out the other day but I don't know if it went through.
Attached is a tutorial based on the Gtk# Demo code.



On Fri, Dec 19, 2008 at 1:28 PM, Mike Kestner <mkest...@gmail.com> wrote:
> On Thu, 2008-12-18 at 15:31 -0600, Austin Winstanley wrote:
>> I'll be happy to write up a tutorial for that...
>
> Nice, send it to me when you have something cooked up and I'll put it on
> the wiki.  Thanks for volunteering.  :-)
>
> --
> Mike Kestner <mkest...@gmail.com>
>
>
>
Gtk Printing Tutorial

    This Printing tutorial steps through and explains in detail the code 
included with the Gtk Demo Application in the Mono install. Gtk# includes 
everything that is needed to draw and print from an app. In this tutorial the 
original code is shown in full first and then stepped through method by method.
    
    The Original Code
    
<code>
    
using System;
using System.IO;
using System.Reflection;
using Gtk;
using Cairo;

namespace GtkDemo
{
        /// <summary>
        /// DemoPrinting - Gtk Printing Demo included with the Gtk Sharp Demo 
Application
        /// </summary>
        [Demo ("Printing", "DemoPrinting.cs")]
        public class DemoPrinting
        {
            private static double headerHeight = (10*72/25.4);
            private static double headerGap = (3*72/25.4);
            private static int pangoScale = 1024;

            private PrintOperation print;

            private string fileName = "DemoPrinting.cs";
            private double fontSize = 12.0;
            private int linesPerPage;
            private string[] lines;
            private int numLines;
            private int numPages;

            /// <summary>
            /// Constructor - Set up the Print Operation
            /// </summary>
            public DemoPrinting ()
            {
                print = new PrintOperation ();
                
                // Set the Print Operation methods
                print.BeginPrint += new BeginPrintHandler (OnBeginPrint);
                print.DrawPage += new DrawPageHandler (OnDrawPage);
                print.EndPrint += new EndPrintHandler (OnEndPrint);

                // Run the Print Operation and tell it what it should do 
(Export, Preview, Print, PrintDialog)
                // And provide a parent window if applicable
                print.Run (PrintOperationAction.PrintDialog, null);
            }

            /// <summary>
            /// OnBeginPrint - Load up the Document to be printed and analyze it
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The BeginPrintArgs passed by the Print 
Operation</param>
            private void OnBeginPrint (object obj, Gtk.BeginPrintArgs args)
            {
                string contents;
                double height;

                // Get the Context of the Print Operation
                PrintContext context = args.Context;
                
                // Get the Height of the Context
                height = context.Height;
              
                // From the FontSize and the Height of the Page determine the 
Lines available per page
                linesPerPage = (int)Math.Floor(height / fontSize);
                
                // Load the file to be printed
                contents = LoadFile("DemoPrinting.cs");

                // Split the Content into seperate lines
                lines = contents.Split('\n');
                
                
                // Get the Number of lines
                numLines = lines.Length;
                
                // Calculate the Number of Pages by how many lines there are 
and how many lines are available per page
                numPages = (numLines - 1) / linesPerPage + 1;
                
                // Tell the Print Operation how many pages there are
                print.NPages = numPages;                        
            }

            /// <summary>
            /// LoadFile - A helper method to load the file to be printed
            /// </summary>
            /// <param name="filename">The Name of the File to load</param>
            /// <returns>Returns the contents of the loaded file in a 
String</returns>
            private string LoadFile (string filename)
            {
                Stream file = Assembly.GetExecutingAssembly 
().GetManifestResourceStream(filename);
              
                if (file == null && File.Exists (filename))
                    file = File.OpenRead (filename);
                                        
                if (file == null)
                    return "File not found";

                StreamReader sr = new StreamReader (file);
                
                return sr.ReadToEnd ();
            }
            
            /// <summary>
            /// OnDrawPage - Draws the Content of each Page to be printed
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The DrawPageArgs passed by the Print 
Operation</param>
            private void OnDrawPage (object obj, Gtk.DrawPageArgs args)
            {
                // Create a Print Context from the Print Operation
                PrintContext context = args.Context;

                // Create a Cairo Context from the Print Context
                Cairo.Context cr = context.CairoContext;
                
                // Get the width of the Print Context
                double width = context.Width;

                // Create a rectangle to be used for the Content
                cr.Rectangle (0, 0, width, headerHeight);
                cr.SetSourceRGB (0.8, 0.8, 0.8);
                cr.FillPreserve ();

                // Create a Stroke to outline the Content
                cr.SetSourceRGB (0, 0, 0);
                cr.LineWidth = 1;
                cr.Stroke();

                // Create a Pango Layout for the Text
                Pango.Layout layout = context.CreatePangoLayout ();
                
                // Set the Font and Font Size desired
                Pango.FontDescription desc = Pango.FontDescription.FromString 
("sans 14");
                layout.FontDescription = desc;
                
                // Create a Header with the FileName and center it on the page
                layout.SetText (fileName);
                layout.Width = (int)width;
                layout.Alignment = Pango.Alignment.Center;

                // Get the Text Height fromt the Height of the layout and the 
Height of the Page
                int layoutWidth, layoutHeight;
                layout.GetSize (out layoutWidth, out layoutHeight);
                double textHeight = (double)layoutHeight / (double)pangoScale;

                // Move to the Footer
                cr.MoveTo (width/2, (headerHeight - textHeight) / 2);
                Pango.CairoHelper.ShowLayout (cr, layout);

                // Set the Page Number in the Footer with a right alignment
                string pageStr = String.Format ("{0}/{1}", args.PageNr + 1, 
numPages);
                layout.SetText (pageStr);
                layout.Alignment = Pango.Alignment.Right;

                cr.MoveTo (width - 2, (headerHeight - textHeight) / 2);
                Pango.CairoHelper.ShowLayout (cr, layout);

                // Create a new Pango Layout for the Content
                layout = null;
                layout = context.CreatePangoLayout ();

                // Set the Description of the Content
                desc = Pango.FontDescription.FromString ("mono");
                desc.Size = (int)(fontSize * pangoScale);
                layout.FontDescription = desc;
                
                // Move to the beginning of the Content, which is after the 
Header Height and Gap
                cr.MoveTo (0, headerHeight + headerGap);
                
                int line = args.PageNr * linesPerPage;
                
                // Draw the lines on the page according to how many lines there 
are left and how many lines can fit on the page
                for (int i=0; i < linesPerPage && line < numLines; i++)
                {
                  layout.SetText (lines[line]);
                  Pango.CairoHelper.ShowLayout (cr, layout);
                  cr.RelMoveTo (0, fontSize);
                  line++;
                }
                
                layout = null;
            }

            /// <summary>
            /// OnEndPrint - Executed at the end of the Print Operation
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The EndPrintArgs passed by the Print 
Operation</param>
            private void OnEndPrint (object obj, Gtk.EndPrintArgs args)
            {
            }
        }
}

</code>

  Step By Step
  
  The Contructor -
    Create a new Print Operation and set its events. When calling Run, provide 
an overload that specifies what you want the operation to do. The options are 
    Export                 Export to a file.
    Preview              Show the print preview.
    Print                  Print with current settings without showing dialog.
    PrintDialog      Show the print dialog.
    
    The second parameter is to provide a parent window if there is one.
  
  <code>

            /// <summary>
            /// Constructor - Set up the Print Operation
            /// </summary>
            public DemoPrinting ()
            {
                print = new PrintOperation ();
                
                // Set the Print Operation methods
                print.BeginPrint += new BeginPrintHandler (OnBeginPrint);
                print.DrawPage += new DrawPageHandler (OnDrawPage);
                print.EndPrint += new EndPrintHandler (OnEndPrint);

                // Run the Print Operation and tell it what it should do 
(Export, Preview, Print, PrintDialog)
                // And provide a parent window if applicable
                print.Run (PrintOperationAction.PrintDialog, null);
            }
            
  </code>
  
  Begin print -
  
  Gets the Print Context from the Print Operation and loads the file that we 
want to Print. In this code the Context is analyzed for Height and lines that 
can be printed on each page. Also gets the total number of lines and the total 
number of pages to be printed.

  <code>

            /// <summary>
            /// OnBeginPrint - Load up the Document to be printed and analyze it
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The BeginPrintArgs passed by the Print 
Operation</param>
            private void OnBeginPrint (object obj, Gtk.BeginPrintArgs args)
            {
                string contents;
                double height;

                // Get the Context of the Print Operation
                PrintContext context = args.Context;
                
                // Get the Height of the Context
                height = context.Height;
              
                // From the FontSize and the Height of the Page determine the 
Lines available per page
                linesPerPage = (int)Math.Floor(height / fontSize);
                
                // Load the file to be printed
                contents = LoadFile("DemoPrinting.cs");

                // Split the Content into seperate lines
                lines = contents.Split('\n');
                
                // Get the Number of lines
                numLines = lines.Length;
                
                // Calculate the Number of Pages by how many lines there are 
and how many lines are available per page
                numPages = (numLines - 1) / linesPerPage + 1;
                
                // Tell the Print Operation how many pages there are
                print.NPages = numPages;                        
            }
            
  </code>
  
  Draw page -

  This is the grunt work of the operation. Here the Print Operation has to get 
a Cairo Context in order to draw all the content on the pages, according to how 
many lines are available and how many pages there are. There is also a Header 
with the FileName and a footer with the Page Number included. Pango Layouts are 
created as a description of the Content to specify font type and font size.
  
  <code>
            
            /// <summary>
            /// OnDrawPage - Draws the Content of each Page to be printed
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The DrawPageArgs passed by the Print 
Operation</param>
            private void OnDrawPage (object obj, Gtk.DrawPageArgs args)
            {
                // Create a Print Context from the Print Operation
                PrintContext context = args.Context;

                // Create a Cairo Context from the Print Context
                Cairo.Context cr = context.CairoContext;
                
                // Get the width of the Print Context
                double width = context.Width;

                // Create a rectangle to be used for the Content
                cr.Rectangle (0, 0, width, headerHeight);
                cr.SetSourceRGB (0.8, 0.8, 0.8);
                cr.FillPreserve ();

                // Create a Stroke to outline the Content
                cr.SetSourceRGB (0, 0, 0);
                cr.LineWidth = 1;
                cr.Stroke();

                // Create a Pango Layout for the Text
                Pango.Layout layout = context.CreatePangoLayout ();
                
                // Set the Font and Font Size desired
                Pango.FontDescription desc = Pango.FontDescription.FromString 
("sans 14");
                layout.FontDescription = desc;
                
                // Create a Header with the FileName and center it on the page
                layout.SetText (fileName);
                layout.Width = (int)width;
                layout.Alignment = Pango.Alignment.Center;

                // Get the Text Height fromt the Height of the layout and the 
Height of the Page
                int layoutWidth, layoutHeight;
                layout.GetSize (out layoutWidth, out layoutHeight);
                double textHeight = (double)layoutHeight / (double)pangoScale;

                // Move to the Footer
                cr.MoveTo (width/2, (headerHeight - textHeight) / 2);
                Pango.CairoHelper.ShowLayout (cr, layout);

                // Set the Page Number in the Footer with a right alignment
                string pageStr = String.Format ("{0}/{1}", args.PageNr + 1, 
numPages);
                layout.SetText (pageStr);
                layout.Alignment = Pango.Alignment.Right;

                cr.MoveTo (width - 2, (headerHeight - textHeight) / 2);
                Pango.CairoHelper.ShowLayout (cr, layout);

                // Create a new Pango Layout for the Content
                layout = null;
                layout = context.CreatePangoLayout ();

                // Set the Description of the Content
                desc = Pango.FontDescription.FromString ("mono");
                desc.Size = (int)(fontSize * pangoScale);
                layout.FontDescription = desc;
                
                // Move to the beginning of the Content, which is after the 
Header Height and Gap
                cr.MoveTo (0, headerHeight + headerGap);
                
                int line = args.PageNr * linesPerPage;
                
                // Draw the lines on the page according to how many lines there 
are left and how many lines can fit on the page
                for (int i=0; i < linesPerPage && line < numLines; i++)
                {
                  layout.SetText (lines[line]);
                  Pango.CairoHelper.ShowLayout (cr, layout);
                  cr.RelMoveTo (0, fontSize);
                  line++;
                }
                
                layout = null;
            }
            
  </code>
  
  End print -
  
  While there is no code here now, this is where the code would go that would 
be executed after the Print Operation has completed.

  <code>

            /// <summary>
            /// OnEndPrint - Executed at the end of the Print Operation
            /// </summary>
            /// <param name="obj">The Print Operation</param>
            /// <param name="args">The EndPrintArgs passed by the Print 
Operation</param>
            private void OnEndPrint (object obj, Gtk.EndPrintArgs args)
            {
            }
            
  </code>
_______________________________________________
Gtk-sharp-list maillist  -  Gtk-sharp-list@lists.ximian.com
http://lists.ximian.com/mailman/listinfo/gtk-sharp-list

Reply via email to