Search code examples
c#winformsprintdocumentprintdialog

print rich text box in a specific tab multiple pages C#


I am doing a web browser with multiple tabs and each tab probably will have a new website differs from the other tabs. now what i am trying to do is to print the page on a specific tab and the page might consists of multiple pages when i am trying to print. this is my code and the problem with the code is it is only printing one page and on the last tab had been opened. any suggestions:

  //this is the printDocemnt from the toolbox
  private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        Font font1 = new Font("Arial", 16, FontStyle.Regular);
        e.Graphics.DrawString(rtb.Text, font1, Brushes.Black, 100, 100);//rtb.Text is a richtextbox object that i initialize in the beginning of the form

    }

    //this is the printbutton just a normal button
    private void PrintButton_Click(object sender, EventArgs e)
    {
        printDialog1.ShowDialog();
        printDocument1.Print();
    }

Solution

  • This is how i did it: the Print document contains this code:

            private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Font font1 = new Font("Arial", 10, FontStyle.Regular);
            //e.Graphics.DrawString(tabsProperties[tabsProperties.IndexOf(new TabProperties(this.tabControl1.SelectedIndex))].TabHtml, font1, Brushes.Black, 100, 100);
    
    
    
            int charactersOnPage = 0;
            int linesPerPage = 0;
    
            // Sets the value of charactersOnPage to the number of characters 
            // of stringToPrint that will fit within the bounds of the page.
            e.Graphics.MeasureString(stringToPrint, font1,
                e.MarginBounds.Size, StringFormat.GenericTypographic,
                out charactersOnPage, out linesPerPage);
    
            // Draws the string within the bounds of the page
            e.Graphics.DrawString(stringToPrint, font1, Brushes.Black,
                e.MarginBounds, StringFormat.GenericTypographic);
    
            // Remove the portion of the string that has been printed.
            stringToPrint = stringToPrint.Substring(charactersOnPage);
    
            // Check to see if more pages are to be printed.
            e.HasMorePages = (stringToPrint.Length > 0);
    
        }
    

    this is the print button:

       private void PrintButton_Click(object sender, EventArgs e)
        {
            stringToPrint = tabsProperties[tabsProperties.IndexOf(new TabProperties(this.tabControl1.SelectedIndex))].TabHtml;
    
            printDialog1.ShowDialog();
            printDocument1.Print();
    
        }