473,566 Members | 3,309 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PrintDocument and HasMorePages issue

Hello,

When using the VB.NET PrintDocument class, I seem to be encountering an
issue where the sub pd_PrintPage handles PrintDocument.P rintPage (upon
continuing if HasMorePages = true) will paint the next page on top of
the original page. In a sample data case where the source is long
enough to fill three pages, I end up with four calls to pd_PrintPage
which render onto two printed sheets. Historical posts in this forum
from 2003 and 2005 suggested several tactics:

1) Explicitly call Exit Sub after setting HasMorePages = true
2) Defining the PrintDocument object in code instead of with the visual
component
3) Avoiding the Addhandler statement before calling pd.Print():
AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage

In my current code, I have implemented # 1 and 2. I was unable to get
any output under #3. Are there any further tactics to try?

I remain suspicious of the AddHandler, though I haven't been able to
work around it yet -- could I have two concurrent pd_PrintPage threads,
rendering to the same target? It seems unlikely, because my page
counter is incremented between these calls.

I thought I had this resolved yesterday with this code as-is, but as it
happens, it worked successfully to print 3 distinct pages under only
one case: where I had put in debugging break at the start of
pd_PrintPage and stepped through all steps.

Even if I put in a few breaks, but "F5" to accelerate between them, the
issue continues to occur. Nevertheless, I've been trying to identify
the specific step (maybe I should introduce an artifical delay? In the
print event model, is there a way to force the pd_PrintPage execution
to wait for, ie, synchronous feedback from the printer before
continuing to render the next page if I suspect the local network to
the printer is slow?)

I once suspected I was sloppy about margins (and have attempted in code
to be somewhat cleaner), and that I may have pixels rendering outside
the printable bounds of the page, but I don't think this would cause
the PrintPage re-iteration to stay on the same sheet. Also, because
the app worked on debug mode with the same data and graphic element
positioning, I no longer suspect this angle. Is this something to
pursue?

Here is the code I'm working with. There is a button click event
handler, a beginPrint which initializes PrintPageCount as a page
counter, and the PrintPage sub, which uses the page counter to
determine which elements from an array of my own user controls
(ComponentColle ction) to render on the page. This also drives my
HasMorePages = T/F logic. PrintALabel and PrintATextbox are overloaded
methods I wrote that apply the offset parameter to the object's
location, and call appropriate graphics.DrawRe ctangle and
graphics.DrawSt ring methods.

'************** *************** *************** *************** *****
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
Try
'Assumes the default printer.
'Dim pd As System.Drawing. Printing.PrintD ocument =
PrintDocument1
pd = New System.Drawing. Printing.PrintD ocument()

Dim margins As New Printing.Margin s(25, 25, 25, 25)
pd.DefaultPageS ettings.Margins = margins

AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
' pd.DefaultPageS ettings.Landsca pe = True
pd.Print()
Catch ex As Exception
MessageBox.Show (ex.Message, "An error occurred while
printing")
End Try
End Sub

'************** *************** *************** *************** ****

Private Sub pd_BeginPrint(B yVal sender As Object, ByVal e As
System.Drawing. Printing.PrintE ventArgs) Handles pd.BeginPrint
PrintPageCount = 0
FormLocation = Me.ComponentCol lection(0).Loca tion
FormLocation.Y = FormLocation.Y -
PrintDocument1. DefaultPageSett ings.HardMargin Y '- 20
FormLocation.X = PrintDocument1. DefaultPageSett ings.HardMargin X
'Me.ScrollContr olIntoView(Me.C omponentCollect ion(0))
End Sub

'************** *************** *************** *************** ****

Private Sub pd_PrintPage(By Val sender As Object, ByVal ev As
System.Drawing. Printing.PrintP ageEventArgs) Handles pd.PrintPage
' Draw a picture.
Dim thisFont As New System.Drawing. Font("Microsoft Sans Serif",
8.25!, CType((System.D rawing.FontStyl e.Regular),
System.Drawing. FontStyle), System.Drawing. GraphicsUnit.Po int, CType(0,
Byte))
Dim thisFormat As New System.Drawing. StringFormat()

'In future, calculate components per page based on size and
paper setting.
Dim ComponentsPerPa ge As Single = 11

Dim indexStart As Integer = PrintPageCount * ComponentsPerPa ge
Dim indexEnd As Integer
Dim LastPage As Boolean = False

If Me.ComponentCol lection.Length - PrintPageCount *
ComponentsPerPa ge <= ComponentsPerPa ge Then
' last page to print
indexEnd = indexStart + Me.ComponentCol lection.Length -
PrintPageCount * ComponentsPerPa ge - 1
LastPage = True
Else
indexEnd = (PrintPageCount + 1) * ComponentsPerPa ge - 1
'indexStart +
End If
''
Me.ScrollContro lIntoView(Me.Co mponentCollecti on(indexStart))

Dim item As SingleComponent Control
Dim i As Integer
' For Each item In Me.ComponentCol lection
For i = indexStart To indexEnd
item = Me.ComponentCol lection(i)

Dim rePoint As New System.Drawing. Point(FormLocat ion.X,
item.Location.Y - PrintPageCount * ComponentsPerPa ge * (item.Height +
5) - FormLocation.Y)
' +5 to height is spacing between components.
item.PrinterCoo rd = rePoint

ev.Graphics.Dra wRectangle(Pens .Gray, item.PrinterCoo rd.X,
item.PrinterCoo rd.Y, item.Width - 80, item.Height)
PrintATextbox(i tem.txtConsumed , item, ev,
Drawing2D.Hatch Style.Percent50 )
PrintATextbox(i tem.txtOnHand, item, ev,
Drawing2D.Hatch Style.Percent05 )
PrintATextbox(i tem.TxtOutstand ing, item, ev,
Drawing2D.Hatch Style.Percent75 )
Dim lblpt As New Point(5, 36)
PrintALabel(ite m.Label1, item, ev, lblpt)
Dim shiftleft As New Point(-50, 0)
PrintALabel(ite m.Label2, item, ev, shiftleft)
' ... etc. Several more labels removed for clarity
PrintALabel(ite m.Label11, item, ev, shiftleft)
Next i

' iterate page count, footer, and test

PrintPageCount = PrintPageCount + 1

'footer with current page number
ev.Graphics.Dra wString("Invent ory/Component Report for Job " +
JobNumber.ToStr ing + " -- Page " + PrintPageCount. ToString, thisFont,
Brushes.Black, 40, 950)
' ev.HasMorePages = False

If Not LastPage Then
ev.HasMorePages = True
Exit Sub
Else
ev.HasMorePages = False
End If
End Sub

'************** *************** *************** ***************
Thank you to anyone for any insight into this issue.

Regards,
Keith Gerritsen

Sep 21 '06 #1
1 11168
I have a solution, but I'm not jazzed by it. I moved the page-count
initialization to the button event, and wrapped a Where around the
pd.Print():
PrintPageCount = 0
Dim LastPage As Boolean = False

While Not LastPage
'try print as separate docs...
'pd.Print()
If Me.ComponentCol lection.Length - PrintPageCount *
ComponentsPerPa ge <= ComponentsPerPa ge Then
' last page to print
LastPage = True
Else
LastPage = False
End If
pd.Print()
PrintPageCount = PrintPageCount + 1
End While

It still calls the PrintPage twice for each page, but as I don't
increment PrintPageCount in this procedure any more, rendering twice on
each output is of no consequence.

I am managing my page counts and printing each page as a separate
1-page document now. It works, and I'm done with this, but I don't
exactly like it. If I was going to implement a "cancel print" feature,
it would be a pain to accomodate.

Regards,
Keith
ki***@drexel.ed u wrote:
Hello,

When using the VB.NET PrintDocument class, I seem to be encountering an
issue where the sub pd_PrintPage handles PrintDocument.P rintPage (upon
continuing if HasMorePages = true) will paint the next page on top of
the original page. In a sample data case where the source is long
enough to fill three pages, I end up with four calls to pd_PrintPage
which render onto two printed sheets. Historical posts in this forum
from 2003 and 2005 suggested several tactics:

1) Explicitly call Exit Sub after setting HasMorePages = true
2) Defining the PrintDocument object in code instead of with the visual
component
3) Avoiding the Addhandler statement before calling pd.Print():
AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage

In my current code, I have implemented # 1 and 2. I was unable to get
any output under #3. Are there any further tactics to try?

I remain suspicious of the AddHandler, though I haven't been able to
work around it yet -- could I have two concurrent pd_PrintPage threads,
rendering to the same target? It seems unlikely, because my page
counter is incremented between these calls.

I thought I had this resolved yesterday with this code as-is, but as it
happens, it worked successfully to print 3 distinct pages under only
one case: where I had put in debugging break at the start of
pd_PrintPage and stepped through all steps.

Even if I put in a few breaks, but "F5" to accelerate between them, the
issue continues to occur. Nevertheless, I've been trying to identify
the specific step (maybe I should introduce an artifical delay? In the
print event model, is there a way to force the pd_PrintPage execution
to wait for, ie, synchronous feedback from the printer before
continuing to render the next page if I suspect the local network to
the printer is slow?)

I once suspected I was sloppy about margins (and have attempted in code
to be somewhat cleaner), and that I may have pixels rendering outside
the printable bounds of the page, but I don't think this would cause
the PrintPage re-iteration to stay on the same sheet. Also, because
the app worked on debug mode with the same data and graphic element
positioning, I no longer suspect this angle. Is this something to
pursue?

Here is the code I'm working with. There is a button click event
handler, a beginPrint which initializes PrintPageCount as a page
counter, and the PrintPage sub, which uses the page counter to
determine which elements from an array of my own user controls
(ComponentColle ction) to render on the page. This also drives my
HasMorePages = T/F logic. PrintALabel and PrintATextbox are overloaded
methods I wrote that apply the offset parameter to the object's
location, and call appropriate graphics.DrawRe ctangle and
graphics.DrawSt ring methods.

'************** *************** *************** *************** *****
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
Try
'Assumes the default printer.
'Dim pd As System.Drawing. Printing.PrintD ocument =
PrintDocument1
pd = New System.Drawing. Printing.PrintD ocument()

Dim margins As New Printing.Margin s(25, 25, 25, 25)
pd.DefaultPageS ettings.Margins = margins

AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
' pd.DefaultPageS ettings.Landsca pe = True
pd.Print()
Catch ex As Exception
MessageBox.Show (ex.Message, "An error occurred while
printing")
End Try
End Sub

'************** *************** *************** *************** ****

Private Sub pd_BeginPrint(B yVal sender As Object, ByVal e As
System.Drawing. Printing.PrintE ventArgs) Handles pd.BeginPrint
PrintPageCount = 0
FormLocation = Me.ComponentCol lection(0).Loca tion
FormLocation.Y = FormLocation.Y -
PrintDocument1. DefaultPageSett ings.HardMargin Y '- 20
FormLocation.X = PrintDocument1. DefaultPageSett ings.HardMargin X
'Me.ScrollContr olIntoView(Me.C omponentCollect ion(0))
End Sub

'************** *************** *************** *************** ****

Private Sub pd_PrintPage(By Val sender As Object, ByVal ev As
System.Drawing. Printing.PrintP ageEventArgs) Handles pd.PrintPage
' Draw a picture.
Dim thisFont As New System.Drawing. Font("Microsoft Sans Serif",
8.25!, CType((System.D rawing.FontStyl e.Regular),
System.Drawing. FontStyle), System.Drawing. GraphicsUnit.Po int, CType(0,
Byte))
Dim thisFormat As New System.Drawing. StringFormat()

'In future, calculate components per page based on size and
paper setting.
Dim ComponentsPerPa ge As Single = 11

Dim indexStart As Integer = PrintPageCount * ComponentsPerPa ge
Dim indexEnd As Integer
Dim LastPage As Boolean = False

If Me.ComponentCol lection.Length - PrintPageCount *
ComponentsPerPa ge <= ComponentsPerPa ge Then
' last page to print
indexEnd = indexStart + Me.ComponentCol lection.Length -
PrintPageCount * ComponentsPerPa ge - 1
LastPage = True
Else
indexEnd = (PrintPageCount + 1) * ComponentsPerPa ge - 1
'indexStart +
End If
''
Me.ScrollContro lIntoView(Me.Co mponentCollecti on(indexStart))

Dim item As SingleComponent Control
Dim i As Integer
' For Each item In Me.ComponentCol lection
For i = indexStart To indexEnd
item = Me.ComponentCol lection(i)

Dim rePoint As New System.Drawing. Point(FormLocat ion.X,
item.Location.Y - PrintPageCount * ComponentsPerPa ge * (item.Height +
5) - FormLocation.Y)
' +5 to height is spacing between components.
item.PrinterCoo rd = rePoint

ev.Graphics.Dra wRectangle(Pens .Gray, item.PrinterCoo rd.X,
item.PrinterCoo rd.Y, item.Width - 80, item.Height)
PrintATextbox(i tem.txtConsumed , item, ev,
Drawing2D.Hatch Style.Percent50 )
PrintATextbox(i tem.txtOnHand, item, ev,
Drawing2D.Hatch Style.Percent05 )
PrintATextbox(i tem.TxtOutstand ing, item, ev,
Drawing2D.Hatch Style.Percent75 )
Dim lblpt As New Point(5, 36)
PrintALabel(ite m.Label1, item, ev, lblpt)
Dim shiftleft As New Point(-50, 0)
PrintALabel(ite m.Label2, item, ev, shiftleft)
' ... etc. Several more labels removed for clarity
PrintALabel(ite m.Label11, item, ev, shiftleft)
Next i

' iterate page count, footer, and test

PrintPageCount = PrintPageCount + 1

'footer with current page number
ev.Graphics.Dra wString("Invent ory/Component Report for Job " +
JobNumber.ToStr ing + " -- Page " + PrintPageCount. ToString, thisFont,
Brushes.Black, 40, 950)
' ev.HasMorePages = False

If Not LastPage Then
ev.HasMorePages = True
Exit Sub
Else
ev.HasMorePages = False
End If
End Sub

'************** *************** *************** ***************
Thank you to anyone for any insight into this issue.

Regards,
Keith Gerritsen
Sep 21 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1191
by: Frnak McKenney | last post by:
Evert: verb. Turn inside out; turn the inner surface of outward. The project I'm working on involves seven or eight reports. They vary from simple ("print this field here, that there, with a header and footer") to more complex ("put field A on the left unless FieldB is nonzero, in which case add it to a bucket and print it at the end of...
3
1366
by: Stijn Vanpoucke | last post by:
Hallo, i'm having troubles by printing on more pages. I have a counter in the PrintDocument1_PrintPage(..) and i would like to start a new page every 3 counts. If tried it this way: If (i + 1) Mod 3 = 0 Then e.HasMorePages = True
4
13100
by: Marcos Beccar Varela | last post by:
Hello to all, I have this form with a PrintDocument named prt_doc, theproblem is that when I invoke the prt_doc.print() it only prints the las page, and not multiple pages. I Also Have a Preview with a PrintPreviewControl and it shows me all the pages, but I still don´t know how to make them print. Thank you all Marcos
2
3344
by: ReidarT | last post by:
I use this code to print a textfile, but it gives me a lot of blank pages. The file contains 9 lines of text. Private strFileName As String = "C:\Sendepost\LoggFil.txt" Private objStreamToPrint As StreamReader Private objPrintFont As Font Private Sub cmdSkrivUt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles...
3
10538
by: islay | last post by:
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,...
6
4594
by: moti | last post by:
Whenever I use PrintDocument.Print() to print a page it goes to PrintDocument_PrintPage and stays there forever unless I set e.HasMorePages to False. When I set it to False it prints the page but is closes the print file. The effect is that it prints all my pages but creates a print job for each page. So if I print 100 pages I get 100 print...
0
1847
by: Scotty | last post by:
Hi, Hope someone can help me I have a datagridview sith data Code below works fine if I print the data if there is only 1 page (without using '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! If intRowPos <= 10 Then e.HasMorePages = False
1
1605
by: Tony Johansson | last post by:
Hello! In the main form I have a multiline textbox where I can enter text. This is named textBoxEdit. Below I have an eventHandler for event BeginPrint called OnBeginPrint for object PrintDocument and an event handler for event PrintPage here called OnPrintPage for object PrintDocument. In the eventhandler OnBeginPrint it seems to me...
16
4509
by: raylopez99 | last post by:
I am running out of printing paper trying to debug this...it has to be trivial, but I cannot figure it out--can you? Why am I not printing text, but just the initial string "howdy"? On the screen, when I open a file, the entire contents of the file is in fact being shown...so why can't I print it later? All of this code I am getting from...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7645
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2085
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.