VB.NET - Print page

Asked By raj thilak
02-Jun-10 08:25 AM
Hi everyone,

I have to create to print the current page by using printer?

I need to take print current page and how ?

can you provide code for it?
  Sagar P replied to raj thilak
02-Jun-10 08:29 AM
Its really easy to print a page using a simple link on a page. Write the following:

<a href="javascript:window.print()">Print Page</a>

OR

btnPrint.Attributes.Add("onclick()","Javascript:window.print()");

When you click this link in your browser a print page will open. You might also be interested in using a separate .CSS file for printing pages. You can find a simple sample by reading a following article: http://www.alistapart.com/articles/goingtoprint/
  Sandra Jain replied to raj thilak
02-Jun-10 08:34 AM
How to Print in ASP.NET 2.0
 
One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows. 
C# 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
 
public class PrintHelper
{
    public PrintHelper()
    {
    }
 
    public static void PrintWebControl(Control ctrl)
    {
        PrintWebControl(ctrl, string.Empty);
    }
 
    public static void PrintWebControl(Control ctrl, string Script)
    {
        StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }
        Page pg = new Page();
        pg.EnableEventValidation = false;
        if (Script != string.Empty)
        {
            pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        pg.DesignerInitialize();
        pg.RenderControl(htmlWrite);
        string strHTML = stringWrite.ToString();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("<script>window.print();</script>");
        HttpContext.Current.Response.End();
    }
}
 
VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports System.Web.SessionState
 
Public Class PrintHelper
    Public Sub New()
    End Sub
 
    Public Shared Sub PrintWebControl(ByVal ctrl As Control)
        PrintWebControl(ctrl, String.Empty)
    End Sub
 
    Public Shared Sub PrintWebControl(ByVal ctrl As Control, ByVal Script As String)
        Dim stringWrite As StringWriter = New StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
        Dim pg As Page = New Page()
        pg.EnableEventValidation = False
        If Script <> String.Empty Then
            pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();</script>")
        HttpContext.Current.Response.End()
    End Sub
End Class
 
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }
VB.NET
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>")
End Sub
The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :
 
PrintHelper.PrintWebControl(Panel1);
 
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
 
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
End Sub

        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
        Dim pg As Page = New Page()
        pg.EnableEventValidation = False
        If Script <> String.Empty Then
            pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();</script>")
        HttpContext.Current.Response.End()
    End Sub
End Class
 
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }
VB.NET
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>")
End Sub
The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :
 
PrintHelper.PrintWebControl(Panel1);
 
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
 
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
End Sub
 
Well that’s it. Try out the sample attached with this article and print any control you desire. The entire source code of this article can be downloaded over http://cid-2c5f5b0560e374cb.skydrive.live.com/self.aspx/.Public/Uploads/PrintingInASPNET.zip.
I hope this article was useful and I thank you for viewing it.
  Sara J replied to raj thilak
02-Jun-10 08:38 AM

To print the document immediately with the default printer, the sample code uses the PreparePrintDocument function to crate PrintDocument and executes the print

Private Sub btnPrint_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnPrint.Click
'Create print document using the preparePrintdocument command
    Dim pDocument As PrintDocument = _
        PreparePrintDocument()
  
    ' Print immediately.
    pDocument .Print()
End Sub

 To print using Print Dialog option use the sample below
 

public Sub OnbtnPrtDlg_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnPrtDlg.Click
    
    dlgPrint.Document = PreparePrintDocument()
  
  
    dlgPrint.ShowDialog()
End Sub

  Devil Scorpio replied to raj thilak
02-Jun-10 09:09 AM
Hi Raj,

You can use  Print Dialogs to print pages.

Let's work with print related controls provided by the .NET Framework. On a new form drag a PrintDialog, PrintDocument, PrintPreviewControl, PrintPreviewDialog, PageSetupDialog, MainMenu and a RichtTextBox contol. Select MainMenu and In the "Type Here" part, type File and under file type Print, PrintPreview, PageSetup and PPControl. The menu should look like this:File->Print, PrintPreview, PageSetup, PPControl. The RichTextBox control is used to load some text in it which will be ready to print. The Form in design view should look like the image below.

Before proceeding further you need to set properties for these dialogs in their properties window. You can set these properties at run time if you wish. Setting them at design time will reduce some lines of code. The necessary changes are listed below.

For PrintDialog1, set the AllowSelection and AllowSomePages properties to True and the Document property to PrintDocument1.

For PrintPreviewDialog1, PageSetupDialog1 and PrintPreviewControl1, set the Document property to PrintDocument1 (for all of them).

Code

Imports System.Drawing.Printing
Public Class Form1 Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
RichTextBox1.Text = "Programmershttp://www.startvbdotnet.com/controls/printdialog1.aspx# have undergone a major change in many years of _
programming various machines. For example, what could take days to create an _
application in other programming languages like C, C++ could be done in hours with _
Visual Basic. Visual Basic provides many interesting sets of tools to aid us in _
building exciting applicationshttp://www.startvbdotnet.com/controls/printdialog1.aspx#. Visual Basic provides these tools to make our _
life far more easier because all the real hard code is already written for us."
'filling the richtextbox with some text that can be used readily
End Sub

Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem2.Click
If PrintDialog1.ShowDialog = DialogResult.OK Then
'showDialog method makes the dialog box visible at run time
PrintDocument1.Print()
End If
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem3.Click
Try
PrintPreviewDialog1.ShowDialog()
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem4.Click
With PageSetupDialog1
.PageSettings = PrintDocument1.DefaultPageSettings
End With
Try
If PageSetupDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings
End If
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub MenuItem5_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem5.Click
Try
PrintPreviewControl1.Document = PrintDocument1
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As_
System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
'PrintPage is the foundational printing event. This event gets fired for every
' page that will be printed
Static intCurrentChar As Int32
' declaring a static variable to hold the position of the last printed char
Dim font As New Font("Verdana", 14)
' initializing the font to be used for printing
Dim PrintAreaHeight, PrintAreaWidth, marginLeft, marginTop As Int32
With PrintDocument1.DefaultPageSettings
' initializing local variables that contain the bounds of the printing area rectangle
PrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
PrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
' initializing local variables to hold margin values that will serve
' as the X and Y coordinates for the upper left corner of the printing
' area rectangle.
marginLeft = .Margins.Left
marginTop = .Margins.Top
' X and Y coordinate
End With

If PrintDocument1.DefaultPageSettings.Landscape Then
Dim intTemp As Int32
intTemp = PrintAreaHeight
PrintAreaHeight = PrintAreaWidth
PrintAreaWidth = intTemp
' if the user selects landscape mode, swap the printing area height and width
End If

Dim intLineCount As Int32 = CInt(PrintAreaHeight / font.Height)
' calculating the total number of lines in the document based on the height of
' the printing area and the height of the font
Dim rectPrintingArea As New RectangleF(marginLeft, marginTop, PrintAreaWidth, PrintAreaHeight)
' initializing the rectangle structure that defines the printing area
Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
'instantiating the StringFormat class, which encapsulates text layout information
Dim intLinesFilled, intCharsFitted As Int32
e.Graphics.MeasureString(Mid(RichTextBox1.Text, intCurrentChar + 1), font,_
New SizeF(PrintAreaWidth, PrintAreaHeight), fmt, intCharsFitted, intLinesFilled)
' calling MeasureString to determine the number of characters that will fit in
' the printing area rectangle
e.Graphics.DrawString(Mid(RichTextBox1.Text, intCurrentChar + 1), font,_
Brushes.Black, rectPrintingArea, fmt)
' print the text to the page
intCurrentChar += intCharsFitted
'advancing the current char to the last char printed on this page
< TextBox1.Text.Length Then
If intCurrentChar e.HasMorePages=True
'HasMorePages tells the printing module whether another PrintPage event should be fired
Else
e.HasMorePages = False
intCurrentChar = 0
End If
End Sub

End Class

The above code will throw exceptions if you don't have a printerhttp://www.startvbdotnet.com/controls/printdialog1.aspx# attached to your machine.

Best Regards :)

  Anoop S replied to raj thilak
02-Jun-10 03:45 PM
the main component for printing the PrintDocument component.  To use this component, just call the Print function and intercept the PrintPage event
refer this code for how to print in VB.Net
http://www.vbdotnetheaven.com/UploadFile/mgold/PrintinginVBNET04202005015906AM/PrintinginVBNET.aspx
Create New Account
help
highlighted in yellow. Any help will be appreciated. Thanks in advance, Aldo. / / Print Setup. oCurrSheet.PageSetup.PrintTitleRows = "$7:$7" ; oCurrSheet.PageSetup.LeftHeader = "&9" + ": &D-&T" + Environment.NewLine + " &P &N"; oCurrSheet.PageSetup.CenterHeader = "&" + "8" + " & \ "Arial, Bold Italic \ "&F"; oCurrSheet.PageSetup.RightHeader = "&" + "8" + ""; oCurrSheet.PageSetup.LeftFooter = "&" + "8" + "Confidential - " + "" + "&" + "6" + Environment.NewLine + "Path: " + "&6&Z&F"; oCurrSheet PageSetup.CenterFooter = "&" + "8" + "" + Environment.UserName + Environment.NewLine + "" + Environment.MachineName; oCurrSheet.PageSetup.RightFooter = "&" + "8" + " & \ "Arial, Bold Italic \ "&A"; oCurrSheet.PageSetup.LeftMargin = oExcel .Application.InchesToPoints(0.25); oCurrSheet.PageSetup.RightMargin = oExcel .Application.InchesToPoints(0.25); oCurrSheet
wsSheet As Worksheet Dim sHeader As String For Each wsSheet In Worksheets With wsSheet sHeader = .PageSetup.LeftHeader .PageSetup.LeftHeader = "" sHeader = .PageSetup.CenterHeader .PageSetup.CenterHeader = "" sHeader = .PageSetup.RightHeader .PageSetup.RightHeader = "" .PrintOut From: = 1, To: = 1 sHeader = .PageSetup.LeftHeader sHeader = .CenterHeader sHeader = .RightHeader .PrintOut From: = 2 End With Next wsSheet End Sub The want this to work in any workbook with different page headers. Thanks! Excel Worksheet Discussions PageSetup (1) ActiveSheet.PageSetup (1) Scenario (1) Sheets (1) Page (1) Worksheet (1) Workbook (1) Macro
to use a spreadsheets cell info as a header (or footer) field? Excel Discussions ActiveSheet.PageSetup.CenterHeader (1) ActiveSheet.PageSetup.PrintArea (1) PageSetup (1) ActiveSheet.PageSetup (1) Excel 2003 (1) Sheets (1) Excel (1) Workbook (1) Put the following macro in the ThisWorkbook code area: Private Sub Workbook_BeforePrint(Cancel As Boolean) v = Range("A1").Value ActiveSheet.PageSetup.CenterHeader = v End Sub - - Gary''s Student - gsnu200738 sorry, your instructions are beyond my level Then you could possbly use code like the portion listed below to help you: ActiveSheet.PageSetup.PrintArea = "" With ActiveSheet.PageSetup .LeftHeader = Sheets("Macro").[A2] & "-" & Sheets("Macro"). [B2] .CenterHeader = Sheets("Macro").[C2] .RightHeader = "" .LeftFooter = "&A" .CenterFooter
document on the back side of the paper? Word VBA Discussions ActiveDocument.BuiltInDocumentProperties (1) Sourcea.PageSetup.BottomMargin (1) Sourcea.PageSetup.RightMargin (1) Target.PageSetup.BottomMargin (1) Target.PageSetup.RightMargin (1) Sourcea.PageSetup.LeftMargin (1) Target.PageSetup.LeftMargin (1) Sourcea.PageSetup.TopMargin (1) The following macro was created for someone who wanted to create a document ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) MsgBox Pages Set sourceb = Documents.Open(FileName: = ". . .") Set target = Documents.Add target.PageSetup.LeftMargin = sourcea.PageSetup.LeftMargin target.PageSetup.RightMargin = sourcea.PageSetup.RightMargin target.PageSetup.TopMargin = sourcea.PageSetup