Printing more than one page in VB.Net using PrintDocument object

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I'm trying to print more than one page using the PrintDocument object.
I set "e.HasMorePages = True" after completeing the first page in the
"PrintDocument1_PrintPage" subroutine, and then "exit sub". When
"PrintDocument1_PrintPage" is called for the second page, it skips to the
code to print the second page and then returns, setting "e.HasMorePages =
False".

Everything seems to work however, when I look at my printout the second page
overwrites the first page. How do I keep the second page from overwriting
the first page?
 
Hi Islay,

I think you may try to run the code example in the link below which works
at my side.
Generally, I think your understanding should be OK. You may try to check
with the code below to see if there is anything different from your code.
PrintDocument.PrintPage Event
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfSystemDrawingPrintingPrintDocumentClassPrintPageTopic.asp

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Peter,

Thanks for the quick response.
I tried the link that you gave, But access was denied so that I couldn't get
to it.

I'm still having the problem.
 
Hi Islay,

It is strange, because the msdn online is a public website.
Also I think you may try to search "PrintDocument.PrintPage Event" in your
local MSDN installation if any.
For your referecne, I post the content of the link for your reference.

=======================================Quote================================
====================
..NET Framework Class Library

PrintDocument.PrintPage Event
Occurs when the output to print for the current page is needed.

[Visual Basic]
Public Event PrintPage As PrintPageEventHandler
[C#]
public event PrintPageEventHandler PrintPage;
[C++]
public: __event PrintPageEventHandler* PrintPage;
[JScript] In JScript, you can handle the events defined by a class, but you
cannot define your own.

Event Data
The event handler receives an argument of type PrintPageEventArgs
containing data related to this event. The following PrintPageEventArgs
properties provide information specific to this event.

Property Description
Cancel Gets or sets a value indicating whether the print job should be
canceled.
Graphics Gets the Graphics used to paint the page.
HasMorePages Gets or sets a value indicating whether an additional page
should be printed.
MarginBounds Gets the rectangular area that represents the portion of the
page inside the margins.
PageBounds Gets the rectangular area that represents the total area of the
page.
PageSettings Gets the page settings for the current page.

Remarks
To specify the output to print, use the Graphics included in the
PrintPageEventArgs. For example, to specify a line of text that should be
printed, draw the text using the Graphics.DrawString method.

In addition to specifying the ouput, you can indicate if there are
additional pages to print by setting the PrintPageEventArgs.HasMorePages
property to true. Individual page settings can also be modified through the
PageSettings and the print job can be canceled by setting the
PrintPageEventArgs.Cancel property to true. The default is false, which
indicates that there are no more pages to print. To print each page of a
document using different page settings, handle the QueryPageSettings event.

To associate the event with your event handler, add an instance of the
PrintPageEventHandler delegate to the event. The event handler is called
whenever the event occurs. For more information about handling events with
delegates, see Events and Delegates.

Example
[Visual Basic, C#, C++] The following example prints the file that is
specified through the command line to the default printer.

[Visual Basic, C#, C++] Note The example assumes that each line fits
within the page width.
[Visual Basic, C#, C++] Use the System.ComponentModel, System.Drawing,
System.Drawing.Printing, System.IO, and System.Windows.Forms namespaces for
this example.

[Visual Basic]
Public Class PrintingExample
Private printFont As Font
Private streamToPrint As StreamReader
Private Shared filePath As String

Public Sub New()
Printing()
End Sub

' The PrintPage event is raised for each page to be printed.
Private Sub pd_PrintPage(sender As Object, ev As PrintPageEventArgs)
Dim linesPerPage As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = Nothing

' Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics)

' Iterate over the file, printing each line.
While count < linesPerPage
line = streamToPrint.ReadLine()
If line Is Nothing Then
Exit While
End If
yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, _
yPos, New StringFormat())
count += 1
End While

' If more lines exist, print another page.
If Not (line Is Nothing) Then
ev.HasMorePages = True
Else
ev.HasMorePages = False
End If
End Sub

' Print the file.
Public Sub Printing()
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Print the document.
pd.Print()
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub 'Printing

' This is the main entry point for the application.
Public Shared Sub Main()
Dim args() As String = System.Environment.GetCommandLineArgs()
Dim sampleName As String = args(0)
If args.Length <> 1 Then
Console.WriteLine("Usage: " & sampleName & " <file path>")
Return
End If
filePath = args(0)
End Sub
End Class


[C#]
public class PrintingExample
{
private Font printFont;
private StreamReader streamToPrint;
static string filePath;


public PrintingExample()
{
Printing();
}

// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line=null;

// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics) ;

// Iterate over the file, printing each line.
while (count < linesPerPage &&
((line=streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString (line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}

// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}

// Print the file.
public void Printing()
{
try
{
streamToPrint = new StreamReader (filePath);
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Print the document.
pd.Print();
}
finally
{
streamToPrint.Close() ;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

// This is the main entry point for the application.
public static void Main(string[] args)
{
string sampleName = Environment.GetCommandLineArgs()[0];
if(args.Length != 1)
{
Console.WriteLine("Usage: " + sampleName +" <file path>");
return;
}
filePath = args[0];
new PrintingExample();
}
}


[C++]
public __gc class PrintingExample
{
private:
Font* printFont;
StreamReader* streamToPrint;
static String* filePath;


public:
PrintingExample()
{
Printing();
}

// The PrintPage event is raised for each page to be printed.
private:
void pd_PrintPage(Object* /*sender*/, PrintPageEventArgs* ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = (float)ev->MarginBounds.Left;
float topMargin = (float)ev->MarginBounds.Top;
String* line=0;

// Calculate the number of lines per page.
linesPerPage = ev->MarginBounds.Height /
printFont->GetHeight(ev->Graphics) ;

// Iterate over the file, printing each line.
while (count < linesPerPage &&
((line=streamToPrint->ReadLine()) != 0))
{
yPos = topMargin + (count * printFont->GetHeight(ev->Graphics));
ev->Graphics->DrawString (line, printFont, Brushes::Black,
leftMargin, yPos, new StringFormat());
count++;
}

// If more lines exist, print another page.
if (line != 0)
ev->HasMorePages = true;
else
ev->HasMorePages = false;
}

// Print the file.
public:
void Printing()
{
try
{
streamToPrint = new StreamReader (filePath);
try
{
printFont = new Font(S"Arial", 10);
PrintDocument* pd = new PrintDocument();
pd->PrintPage += new PrintPageEventHandler(this,
&PrintingExample::pd_PrintPage);
// Print the document.
pd->Print();
}
__finally
{
streamToPrint->Close() ;
}
}
catch(Exception* ex)
{
MessageBox::Show(ex->Message);
}
}

static void Main()
{
String* args[] = Environment::GetCommandLineArgs();
String* sampleName = args[0];
if(args->Length != 2)
{
Console::WriteLine(S"Usage: {0} <file path>", sampleName);
return;
}
filePath = args[1];
new PrintingExample();
}
};

int main()
{
PrintingExample::Main();
}

[JScript] No example is available for JScript. To view a Visual Basic, C#,
or C++ example, click the Language Filter button in the upper-left corner
of the page.

Requirements
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows
2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003
family

See Also
PrintDocument Class | PrintDocument Members | System.Drawing.Printing
Namespace | PrintPageEventHandler | PrintPageEventArgs | BeginPrint |
EndPrint | QueryPageSettings | Graphics | PrintDocument Members (Visual J#
Syntax)Printing Graphics in Windows FormsPrinting Text in Windows
FormsCode: Displaying Print Preview for a Windows Form (Visual
Basic)Managed Extensions for C++ Programming&nbsp;


Syntax based on .NET Framework version 1.1.
Documentation version 1.1.1.




Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top