Print to next page - vb.net

I have read a lot of different posts on printing to more pages in VB.NET. For some reason I'm not getting it to work, however. I have e.hasmorepages set to True once the yPosition goes over 1000. Instead of going to the next page, however, it's overwriting starting from the top. What am I doing wrong here? This is a school project.
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
'Declare variables for printing position, strings, and state name
Dim yPos As Integer = 40
Dim xPos As Integer = 25
Dim strLine1 As String = String.Empty
Dim strLine2 As String = String.Empty
Dim strLine3 As String = String.Empty
Dim strLine4 As String = String.Empty
Dim strLine5 As String = String.Empty
For i = 0 To (lstRecords.Items.Count - 1)
'Concatenate strings for printing
strLine1 = "Record Name: " & gVinyl(i).Name
strLine2 = "Artist: " & gVinyl(i).Artist
strLine3 = "Released: " & gVinyl(i).Year
strLine4 = "Contains: " & gVinyl(i).Tracks.ToString & " tracks running " & gVinyl(i).Duration & " minutes"
strLine5 = "Size: " & gVinyl(i).Size.ToString & " inches Speed: " & gVinyl(i).Speed.ToString & " RPM"
'Multiple page print
If yPos > 1000 Then
e.HasMorePages = True
yPos = 40
End If
'Position each string line for printing
e.Graphics.DrawString(strLine1, New Font("Times New Roman", 11), Brushes.Black, xPos, yPos)
yPos += 20
e.Graphics.DrawString(strLine2, New Font("Times New Roman", 11), Brushes.Black, xPos, yPos)
yPos += 20
e.Graphics.DrawString(strLine3, New Font("Times New Roman", 11), Brushes.Black, xPos, yPos)
yPos += 20
e.Graphics.DrawString(strLine4, New Font("Times New Roman", 11), Brushes.Black, xPos, yPos)
yPos += 20
e.Graphics.DrawString(strLine5, New Font("Times New Roman", 11), Brushes.Black, xPos, yPos)
yPos += 50
Next
'Last page printed
e.HasMorePages = False
End Sub

Hans answered this:
You have to add Exit Sub so it will start printing the page. Then the event fires again to print the next page. You do not want to start at 0 again. So make i a field of your class. Set it to 0 with the BeginPrint event.
THANK YOU HANS!

Related

How to remove the time in my Date column when printing

i have a program that print a datagridview and have a date column in it.
the column display date only but when i try to print it, it will have time add how can i remove it?
this is how it looks in the datagridview
and this is my printpreview
print code
Try
dgvInventoryLog.Columns(6).DefaultCellStyle.Format = "dd/MM/yyyy"
Dim actualWidth As Integer = dgvInventoryLog.Columns.Cast(Of DataGridViewColumn).Sum(Function(c) c.Width)
Dim percentage As Decimal = CDec(((100 / actualWidth) * e.MarginBounds.Width) / 100)
Dim header As String = "Inventory Log"
Dim footer As String
Dim startX As Integer = e.MarginBounds.Left
Dim startY As Integer = e.MarginBounds.Top
Dim r As Rectangle
Dim headerFont As New Font(dgvInventoryLog.Font.FontFamily, 15, FontStyle.Italic, GraphicsUnit.Pixel)
Dim szf As SizeF = e.Graphics.MeasureString(header, headerFont)
e.Graphics.DrawString(header, headerFont, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - szf.Width) / 2, startY - szf.Height)
footer = "Page " & pageCounter.ToString
szf = e.Graphics.MeasureString(footer, headerFont)
e.Graphics.DrawString(footer, headerFont, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - szf.Width) / 2, e.MarginBounds.Bottom + 5)
startY += 5
'this is the text alignment
Dim sf As New StringFormat
sf.Alignment = StringAlignment.Center
sf.LineAlignment = StringAlignment.Center
Dim gridFont As New Font(dgvInventoryLog.Font.FontFamily, dgvInventoryLog.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel)
' If startRow = 0 Then
For x As Integer = 0 To dgvInventoryLog.Columns.Count - 1
r.X = startX
r.Y = startY
r.Width = CInt(dgvInventoryLog.Columns(x).Width * percentage)
r.Height = dgvInventoryLog.Rows(0).Height
e.Graphics.DrawRectangle(Pens.Black, r)
e.Graphics.DrawString(dgvInventoryLog.Columns(x).HeaderText, gridFont, Brushes.Black, r, sf)
startX += r.Width
Next
startY += r.Height
' End If
For y As Integer = startRow To dgvInventoryLog.Rows.Count - 1
If y = dgvInventoryLog.NewRowIndex Then Continue For
startX = e.MarginBounds.Left
For x As Integer = 0 To dgvInventoryLog.Columns.Count - 1
r.X = startX
r.Y = startY
r.Width = CInt(dgvInventoryLog.Columns(x).Width * percentage)
r.Height = dgvInventoryLog.Rows(0).Height
e.Graphics.DrawRectangle(Pens.Black, r)
e.Graphics.DrawString(If(Not dgvInventoryLog.Rows(y).Cells(x).Value Is Nothing, dgvInventoryLog.Rows(y).Cells(x).Value.ToString, ""),
gridFont, Brushes.Black, r, sf)
startX += r.Width
Next
startY += r.Height
If startY >= e.MarginBounds.Bottom - 10 Then
If y < dgvInventoryLog.Rows.Count - 1 Then
e.HasMorePages = True
pageCounter += 1
startRow = y + 1
Exit For
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
''preview button
pageCounter = 1
startRow = 0
ppd.Document = pd
ppd.WindowState = FormWindowState.Maximized
ppd.ShowDialog()
End Sub
Private Sub getInventoryLog()
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\INVENTORY_DB.accdb")
Dim cmd As New OleDbCommand("Select ItemCode as [ITEM CODE], ItemName AS [ITEM NAME], Description AS [DESCRIPTION], Price AS [PRICE],
Unit AS [UNIT], Quantity AS [QUANTITY], MovementDate AS [MOVEMENT DATE], `From` AS [FROM],
`To` AS [TO] From [Items Movement]", conn)
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
dgvInventoryLog.Columns.Clear()
dgvInventoryLog.DataSource = dt
dgvInventoryLog.Columns(0).Width = 80
dgvInventoryLog.Columns(1).Width = 250
dgvInventoryLog.Columns(2).Width = 150
dgvInventoryLog.Columns(3).Width = 70
dgvInventoryLog.Columns(4).Width = 70
dgvInventoryLog.Columns(5).Width = 100
dgvInventoryLog.Columns(6).Width = 110
dgvInventoryLog.Columns(7).Width = 135
dgvInventoryLog.Columns(8).Width = 135
End Using
End Sub
this is where i get the code for printing. i dont quite understand it, but its working just fine so i just copy paste it, so if that is where i messed up i will be grateful for pointing it out for me. thanks
https://www.vbforums.com/showthread.php?872037-RESOLVED-Need-help-with-printing-datagridview-content
Inside your loop, check if it's the 7th column (index 6), then convert the value to date and format it as you wish
For x As Integer = 0 To dgvInventoryLog.Columns.Count - 1
r.X = startX
r.Y = startY
r.Width = CInt(dgvInventoryLog.Columns(x).Width * percentage)
r.Height = dgvInventoryLog.Rows(0).Height
e.Graphics.DrawRectangle(Pens.Black, r)
If x = 6 Then
Dim movementDate As Date = Ctype(dgvInventoryLog.Rows(y).Cells(x).Value, Date)
e.Graphics.DrawString(movementDate.ToString("MM/dd/yyyy"),
gridFont, Brushes.Black, r, sf)
' or dd/MM/yyyy
Else
e.Graphics.DrawString(If(Not dgvInventoryLog.Rows(y).Cells(x).Value Is Nothing, dgvInventoryLog.Rows(y).Cells(x).Value.ToString, ""),
gridFont, Brushes.Black, r, sf)
End If
startX += r.Width
Next
You can make it so that the printing code respects the formatting in all columns, regardless of data type.
Dim value = dgvInventoryLog.Rows(y).Cells(x).Value
Dim format = dgvInventoryLog.Columns(x).DefaultCellStyle.Format
Dim text = If(String.IsNullOrEmpty(format),
value.ToString(),
String.Format($"{{0:{format}}}", value))
e.Graphics.DrawString(text, gridFont, Brushes.Black, r, sf)
That will work for any type and any legitimate format and it will also work with empty cells, whether they contain Nothing or DBNull.Value. What gets printed will be the same as what is displayed in the grid regardless.
This bit:
String.Format($"{{0:{format}}}", value)
might look a bit weird, so let me explain. The $ indicates string interpolation. Anything wrapped in braces within that interpolated string is evaluated and replaced with the result, with literal braces escaped with another brace. If, for instance, format contained "dd/MM/yyyy", $"{{0:{format}}}" would produce "{0:dd/MM/yyyy}". When that gets passed to String.Format, it is replaced with the contents of value in the specified format.
EDIT:
Note that, if you prefer, this:
Dim text = If(String.IsNullOrEmpty(format),
value.ToString(),
String.Format($"{{0:{format}}}", value))
could be replaced with this:
Dim text = String.Format(If(String.IsNullOrEmpty(format),
"{0}",
$"{{0:{format}}}"),
value)

Understanding Datagridview Printing

hello guys i just need help in understanding this block of code.
this code is a datagridview printing code that i want to edit to suit my needs but i dont know where to start i tried searching youtube tutorial but i cant seem to find any that explain this(printdocument control). so i want to make the margin a little narrow and to change font for column header and records. i tried changing default/properities of the datagridview and exploring a bit changing all numbers i see in the block of code but i cant seem to understand how it works. and if possible i also want to add a header where i can put a logo.
Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pd.PrintPage
Try
Dim actualWidth As Integer = dgvInventoryLog.Columns.Cast(Of DataGridViewColumn).Sum(Function(c) c.Width)
Dim percentage As Decimal = CDec(((100 / actualWidth) * e.MarginBounds.Width) / 100)
Dim header As String = "Inventory Log"
Dim footer As String
Dim startX As Integer = e.MarginBounds.Left
Dim startY As Integer = e.MarginBounds.Top
Dim r As Rectangle
Dim headerFont As New Font(dgvInventoryLog.Font.FontFamily, 15, FontStyle.Italic, GraphicsUnit.Pixel)
Dim szf As SizeF = e.Graphics.MeasureString(header, headerFont)
e.Graphics.DrawString(header, headerFont, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - szf.Width) / 2, startY - szf.Height)
footer = "Page " & pageCounter.ToString
szf = e.Graphics.MeasureString(footer, headerFont)
e.Graphics.DrawString(footer, headerFont, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - szf.Width) / 2, e.MarginBounds.Bottom + 5)
startY += 5
'this is the text alignment
Dim sf As New StringFormat
sf.Alignment = StringAlignment.Center
sf.LineAlignment = StringAlignment.Center
Dim gridFont As New Font(dgvInventoryLog.Font.FontFamily, dgvInventoryLog.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel)
' If startRow = 0 Then
For x As Integer = 0 To dgvInventoryLog.Columns.Count - 1
r.X = startX
r.Y = startY
r.Width = CInt(dgvInventoryLog.Columns(x).Width * percentage)
r.Height = dgvInventoryLog.Rows(0).Height
e.Graphics.DrawRectangle(Pens.Black, r)
e.Graphics.DrawString(dgvInventoryLog.Columns(x).HeaderText, gridFont, Brushes.Black, r, sf)
startX += r.Width
Next
startY += r.Height
' End If
For y As Integer = startRow To dgvInventoryLog.Rows.Count - 1
If y = dgvInventoryLog.NewRowIndex Then Continue For
startX = e.MarginBounds.Left
For x As Integer = 0 To dgvInventoryLog.Columns.Count - 1
r.X = startX
r.Y = startY
r.Width = CInt(dgvInventoryLog.Columns(x).Width * percentage)
r.Height = dgvInventoryLog.Rows(0).Height
e.Graphics.DrawRectangle(Pens.Black, r)
' e.Graphics.DrawString(If(Not dgvInventoryLog.Rows(y).Cells(x).FormattedValue Is Nothing, dgvInventoryLog.Rows(y).Cells(x).Value.ToString, ""),
'gridFont, Brushes.Black, r, sf)
If x = 6 Then
Dim movementDate As Date = CType(dgvInventoryLog.Rows(y).Cells(x).Value, Date)
e.Graphics.DrawString(movementDate.ToString("dd/MM/yyyy"),
gridFont, Brushes.Black, r, sf)
' or dd/MM/yyyy
Else
e.Graphics.DrawString(If(Not dgvInventoryLog.Rows(y).Cells(x).Value Is Nothing, dgvInventoryLog.Rows(y).Cells(x).Value.ToString, ""),
gridFont, Brushes.Black, r, sf)
End If
startX += r.Width
Next
startY += r.Height
If startY >= e.MarginBounds.Bottom - 10 Then
If y < dgvInventoryLog.Rows.Count - 1 Then
e.HasMorePages = True
pageCounter += 1
startRow = y + 1
Exit For
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
this is the output
ps: im not that experience in stackoverflow(im always just copying code here and there) so if this is not where i should post question like this i will be grateful if you can direct me to the proper place.

How to print datagridview data in horizontal line with printdocument?

I have a query in the SqlServer database, the result of that query is played inside a Datagridview, the result can contain from 0 to 100 data or even more if you doubt it.
I'm trying to print the "Identification" column of Datagridview horizontally, but without success. I have researched in several places and nothing too.
screenshot of form with DataGridView
Follow the form code:
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Drawing.Printing
Public Class frm_relatorio_entregas
' Variables used in the module
Dim RelatorioTitulo As String ' Report title
Dim paginaatual As Integer ' Page number being printed
Dim LinhaAtual As Integer ' Current line number being printed
Dim LinhasporPagina As Integer ' Number of lines per page
Dim PosicaoDaLinha As Single ' Position of the line being printed
Dim registro As Integer ' Record being printed
Private Sub Imprimir()
RelatorioTitulo = "Delivery Report"
Dim doc As PrintDocument = New PrintDocument
AddHandler doc.PrintPage, New Printing.PrintPageEventHandler(AddressOf Me.pdRelatorios_Printpage)
AddHandler doc.BeginPrint, New Printing.PrintEventHandler(AddressOf Me.Begin_Print)
Dim dialogo As PrintDialog = New PrintDialog
'dialogo.Document = doc
' If (dialogo.ShowDialog = DialogResult.OK) Then
Dim preview As PrintPreviewDialog = New PrintPreviewDialog()
preview.Document = doc
preview.WindowState = FormWindowState.Maximized
preview.PrintPreviewControl.Zoom = 1.0
preview.ShowDialog()
'End If
End Sub
Private Sub Begin_Print(ByVal sender As Object, ByVal e As Printing.PrintEventArgs)
' Assigning values ​​to variables at the start of printing
LinhaAtual = 0
paginaatual = 1
PosicaoDaLinha = 0
registro = 0
End Sub
Private Sub pdRelatorios_Printpage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
' Margin variables (e.MarginBounds obtain the rectangular area that represents the part of the page within the margins.)
Dim MargemEsquerda As Single = e.MarginBounds.Left
Dim MargemDireita As Single = e.MarginBounds.Right
Dim MargemSuperior As Single = e.MarginBounds.Top
Dim MargemInferios As Single = e.MarginBounds.Bottom
'Pen class defines an object used to define lines and curves
Dim CanetaDaImpressora As Pen = New Pen(Color.Black, 1)
'Variables of the fonts used (the font class defines a specific format for text, including font face, size and style attributes.
Dim FonteNegrito As Font
Dim FonteTitulo As Font
Dim FonteSubTitulo As Font
Dim FonteRodape As Font
Dim FonteNormal As Font
Dim font1 As Font
'Define effects on fonts used
FonteNegrito = New Font("Arial", 9, FontStyle.Bold)
FonteTitulo = New Font("Arial", 13, FontStyle.Bold)
FonteSubTitulo = New Font("Arial", 9, FontStyle.Bold)
FonteRodape = New Font("Arial", 8)
FonteNormal = New Font("Calibri", 9)
font1 = New Font("Segoe UI", 8, FontStyle.Bold)
'Print the title of the report
e.Graphics.DrawString(RelatorioTitulo, FonteTitulo, Brushes.Black, MargemEsquerda + 200, 30, New StringFormat)
If DateTimePicker1.Value = DateTimePicker1.Value Then
e.Graphics.DrawString(DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
Else
e.Graphics.DrawString(DateTimePicker1.Value & " - " & DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
End If
'Define the number of lines per page
LinhasporPagina = CInt(e.MarginBounds.Height / New Font("Calibri", 18).GetHeight(e.Graphics) - 2)
While (LinhaAtual <= LinhasporPagina AndAlso registro <= DataGridView1.Rows.Count - 1)
PosicaoDaLinha = MargemSuperior + (LinhaAtual * New Font("Calibri", 18).GetHeight(e.Graphics) + 30)
e.Graphics.DrawString(DataGridView1.Rows(registro).Cells(0).Value.ToString, New Font("Calibri", 8, FontStyle.Bold), Brushes.Black, 30, PosicaoDaLinha, New StringFormat())
'Increment record
registro += 1
'increment line
LinhaAtual += 1
End While
'baseboard
e.Graphics.DrawLine(CanetaDaImpressora, 20, MargemInferios + 15, 1150, MargemInferios + 15)
e.Graphics.DrawString(System.DateTime.Now.ToString(), FonteRodape, Brushes.Black, 30, MargemInferios + 15, New StringFormat())
e.Graphics.DrawString("Página : " & paginaatual, FonteRodape, Brushes.Black, 1070, MargemInferios + 15, New StringFormat)
'Increase the page number
paginaatual += 1
'Here check if you are going to open a new page
If (LinhaAtual > LinhasporPagina) Then
' When you open a new page, you have to reset LlinhaAtual
e.HasMorePages = True
LinhaAtual = 0
Else
e.HasMorePages = False
End If
End Sub
Private Sub frm_relatorio_entregas_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtcod.Clear()
txtrazao.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
ComboBox1.SelectedIndex = 0
txtcod.Select()
End Sub
Private Sub txtcod_KeyUp(sender As Object, e As KeyEventArgs) Handles txtcod.KeyUp
If e.KeyCode = Keys.F2 Then
frm_consulta_cliente_cadastro.ShowDialog()
End If
End Sub
Private Sub consulta()
DataGridView1.Rows.Clear()
Cursor.Current = Cursors.WaitCursor
Dim consultando As New frm_aguarde_consultando
consultando.Show()
' Set cursor as hourglass
Application.DoEvents()
Dim ano, mes, dia As Integer
Dim var1data, var2data As Date
Dim dinicio, dfim As String
var1data = DateTimePicker1.Value '.ToString.Substring(0, 10)
dia = var1data.Day
mes = var1data.Month
ano = var1data.Year
dinicio = ano & "-" & mes & "-" & dia
var2data = DateTimePicker2.Value
dia = var2data.Day
mes = var2data.Month
ano = var2data.Year
dfim = ano & "-" & mes & "-" & dia
Using sqlcoon As SqlConnection = GetConnectionsql()
Dim READER As SqlDataReader
Try
sqlcoon.Open()
Dim Query As String
Query = "select MOV_IDENTIFICACAO,MOV_PROTOCOLO,MOV_DATADOC,MOV_SITUACAO,MOV_DATAENTREGA,MOV_HORAENTREGA,MOV_SITEND_CODIGO
from movimento where MOV_DATADOC = '" & dinicio & "'
AND MOV_CLI_CODIGO = '" & txtcod.Text & "' AND MOV_SITUACAO = '" & "E" & "'
AND CAST(MOV_DATAENTREGA AS DATE) = '" & dfim & "' "
Dim COMMAND As SqlCommand = New SqlCommand(Query, sqlcoon)
READER = COMMAND.ExecuteReader
While READER.Read
Dim MOV_IDENTIFICACAO = READER("MOV_IDENTIFICACAO")
Dim MOV_DATADOC = READER("MOV_DATADOC")
Dim MOV_DATAENTREGA = READER("MOV_DATAENTREGA")
Dim MOV_PROTOCOLO = READER("MOV_PROTOCOLO")
Dim MOV_SITUACAO = READER("MOV_SITUACAO")
Dim MOV_SITEND_CODIGO = READER("MOV_SITEND_CODIGO")
DataGridView1.Rows.Add(MOV_IDENTIFICACAO, MOV_PROTOCOLO, MOV_DATADOC, MOV_SITUACAO, MOV_DATAENTREGA, MOV_SITEND_CODIGO)
End While
READER.Close()
sqlcoon.Close()
''--------------'''''''''
Label9.Text = DataGridView1.Rows.Count
For Each linha In DataGridView1.Rows
Dim altura As Integer = 17
linha.height = altura
Next
If DataGridView1.Rows.Count >= 0 Then
' Set cursor as default arrow
Cursor.Current = Cursors.Default
' Hide the please wait form
consultando.Hide()
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
' sqlcoon.Dispose()
End Try
sqlcoon.Open()
Try
For r As Integer = 0 To DataGridView1.Rows.Count - 1
Dim COMMAND3 As SqlCommand
Dim READER3 As SqlDataReader
Dim Query_3 As String
Query_3 = "select IMOV_CODIGORECBTO from imovimento where IMOV_MOV_IDENTIFICACAO ='" & DataGridView1.Rows(r).Cells(0).Value.ToString & "'"
COMMAND3 = New SqlCommand(Query_3, sqlcoon)
READER3 = COMMAND3.ExecuteReader
While READER3.Read
Dim IMOV_CODIGORECBTO = READER3("IMOV_CODIGORECBTO")
'DataGridView1.Columns(6).HeaderCell.Value = "ID"
DataGridView1.Rows(r).Cells(6).Value = IMOV_CODIGORECBTO
End While
READER3.Close()
Next
DataGridView1.Sort(DataGridView1.Columns(6), ListSortDirection.Ascending)
sqlcoon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
consulta()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Imprimir()
End Sub
End Class
screenshot of what is currently being printed
screenshot of I would like the result to be:
Would anyone have any ideas, tools or means to help me? I thank.
An alternative would be to:
Get just the column values that you want.
Join the values from #1 using a delimiter, such as a tab.
Use the Graphics.DrawString method (documentation) for the value from #2.
There will need to be some considerations:
You will need to measure the string from #3 to see if it exceeds the bounds of your print document
If so, then you will need to print multiple pages, picking up where you left off.
Update
Per the OP's request, here is an example. Keep in mind that it doesn't account for the considerations listed above. That will take a bit of effort in debugging to account for those points:
Private Sub pdRelatorios_PrintPage(sender As Object, e As PrintPageEventArgs) Handles pdRelatorios.PrintPage
Dim title = "Relatorio de Entregas"
Dim titleFont = New Font(Font.FontFamily, Convert.ToSingle(Font.Size * 1.5), FontStyle.Bold)
Dim titlePosition = New PointF(Convert.ToSingle(e.MarginBounds.X * 2 - e.PageBounds.Width / 2), e.MarginBounds.Y)
Dim titleSize = e.Graphics.MeasureString(title, titleFont)
e.Graphics.DrawString(title, titleFont, SystemBrushes.ControlText, titlePosition)
Dim cellValues = DataGridView1.Rows.Cast(Of DataGridViewRow).Select(Function(row) row.Cells(0)?.Value?.ToString())
Dim joinedCellValues = String.Join(Constants.vbTab, cellValues)
Dim bodyBounds = New RectangleF(e.MarginBounds.X, Convert.ToSingle(titleSize.Height + e.MarginBounds.Y), e.PageBounds.Width - e.MarginBounds.X * 2, e.PageBounds.Height - e.MarginBounds.Y * 2)
e.Graphics.DrawString(joinedCellValues, Font, SystemBrushes.ControlText, bodyBounds)
End Sub

vb PrintDocument not printing within specified margins

I am using the following code to print but every time I print to a laser printer, the right and bottom margins get cut off regardless of what I set my margins at. Could anyone shed some light on this situation? Note, I have tried using PrintDoc.OriginAtMargins = True/False but it doesn't appear to be working either.
/code/
Public MarginSize As Integer = 15
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'temp = Nothing
'With dgView
' For Each row In dgView.Rows
' temp += row.Cells(0).Value & " " & row.Cells(1).Value & " " & row.Cells(2).Value & " " & row.Cells(3).Value & vbNewLine
' Next
'End With
PrintDialog.PrinterSettings = PrintDoc.PrinterSettings
If PrintDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDoc.PrinterSettings = PrintDialog.PrinterSettings
Dim PageSetup As New PageSettings
With PageSetup
.Margins.Left = MarginSize
.Margins.Right = MarginSize
.Margins.Top = MarginSize
.Margins.Bottom = MarginSize
.Landscape = False
End With
PrintDoc.DefaultPageSettings = PageSetup
End If
' PrintDoc.OriginAtMargins = False
PrintPreviewDialog.Document = PrintDoc
PrintPreviewDialog.WindowState = FormWindowState.Maximized
PrintPreviewDialog.PrintPreviewControl.Zoom = 1
PrintPreviewDialog.ShowDialog()
End Sub
Private Sub PrintDoc_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDoc.PrintPage
Static intStart As Integer
Dim fntText As Font = txtDrawnBy.Font
Dim txtHeight As Integer
Dim LeftMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Left
Dim RightMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Width - MarginSize
Dim TopMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Top
Dim BottomMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Height - MarginSize
txtHeight = PrintDoc.DefaultPageSettings.PaperSize.Height - PrintDoc.DefaultPageSettings.Margins.Top - PrintDoc.DefaultPageSettings.Margins.Bottom
Dim LinesPerPage As Integer = CInt(Math.Round(txtHeight / (fntText.Height + 0.025)))
'Draw Rectangle for Margin
e.Graphics.DrawRectangle(Pens.Red, e.MarginBounds)
Dim y1 As Integer = e.PageBounds.Height.ToString / 3
Dim y2 As Integer = e.PageBounds.Height.ToString / 3 * 2
'Draw line 1/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y1, RightMargin, y1)
'Draw line 3/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y2, RightMargin, y2)
Dim intLineNumber As Integer
Dim sf As New StringFormat
Dim LineStep As Integer = 0
For intCounter = intStart To 66
'Print line numbers
e.Graphics.DrawString(intLineNumber.ToString & ": ", fntText, Brushes.Black, LeftMargin, fntText.Height * intLineNumber + TopMargin)
intLineNumber += 1
If intLineNumber > LinesPerPage Then
intStart = intCounter
e.HasMorePages = True
Exit For
End If
Next
End Sub
I have also attached an image of my results.
Image of print results

Printing Records from ODBC Connection - Stuck on First Page

I am printing records from an ODBC connection but I am not able to print more than the first page. The code I have below generates multiple copies of the same first page. How can I iterate through my records and still create page breaks when necessary?
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
'MsgBox("Printing functionality is still under construction.", MsgBoxStyle.Information)
Dim RecordDoc As Drawing.Printing.PrintDocument
RecordDoc = New Drawing.Printing.PrintDocument
With RecordDoc.DefaultPageSettings
.Landscape = False
.Margins.Left = 50
.Margins.Right = 50
.Margins.Top = 50
.Margins.Bottom = 50
End With
RecordDoc.DocumentName = "Print Records"
AddHandler RecordDoc.PrintPage, AddressOf Me.printrecords
dlgPreview.Document = RecordDoc
dlgPreview.ShowDialog()
RecordDoc.Dispose()
End Sub
Private Sub PrintRecords(ByVal sender As Object, ByVal e As Drawing.Printing.PrintPageEventArgs)
Dim lvi As ListViewItem
Dim Conn As OdbcConnection
Dim Reader As OdbcDataReader
Dim strFname As String = ""
Dim strLname As String = ""
Dim strReportHdr As String = ""
Dim strMainCategory As String = ""
Dim strColumnHeader As String = ""
Dim intLinesPerPage As Integer = 0
Dim x, y As Single
Dim myfont As Font = New Font("Arial", 12, FontStyle.Regular)
Dim myPen As New Pen(Color.Black, 3)
'DEFINE THE REPORT HEADER BASED ON LISTVIEW SELECTIONS
'FIRST, GET THE COLUMN NUMBER SELECTED. YOU'LL USE THIS FOR THE REPORT HEADER AS WELL AS WHEN PRINTING DATA
Dim PrintColHeader As ColumnHeader = ListView1.Columns(intLViewColSort)
'REMOVE THE < OR > AS NECESSARY, IF PRESENT
If PrintColHeader.Text.StartsWith("> ") Then
strColumnHeader = Mid(PrintColHeader.Text, 3) & ", in descending order"
ElseIf PrintColHeader.Text.StartsWith("< ") Then
strColumnHeader = Mid(PrintColHeader.Text, 3) & ", in ascending order"
End If
If rdoCustInfo.Checked = True Then
strMainCategory = "Customer Information"
ElseIf rdoCustVendPrefs.Checked = True Then
strMainCategory = "Customer Vendor Preferences"
ElseIf rdoPricePts.Checked = True Then
strMainCategory = "Customer Price Points"
ElseIf rdoSalesHist.Checked = True Then
strMainCategory = "Customer Sales History"
ElseIf rdoSpecific.Checked = True Then
strMainCategory = "Other"
Else
MsgBox("System error with print function. Have a glass of wine.", MsgBoxStyle.Critical)
Exit Sub
End If
y = e.MarginBounds.Y
x = e.MarginBounds.X
e.Graphics.DrawRectangle(myPen, e.MarginBounds.X, e.MarginBounds.Y + 20, 500, 1)
e.Graphics.DrawString(strMainCategory & " - " & strColumnHeader, myfont, Brushes.Black, x, y)
y += CInt(2 * myfont.GetHeight(e.Graphics))
myfont = New Font("Arial", 10, FontStyle.Regular)
intLinesPerPage = e.MarginBounds.Height / myfont.GetHeight(e.Graphics)
'Open Connection TO ASC
Conn = New OdbcConnection(ConnString)
Conn.Open()
For Each lvi In ListView1.Items
'Execute Query
cmdString = "select lastname,firstname,street1,street2,city,state,zipcode,phonenum,emailaddress from customer where customernum=" & lvi.Text
Dim Cmd As New OdbcCommand(cmdString, Conn)
Reader = Cmd.ExecuteReader()
'Process The Result Set
While (Reader.Read())
Dim tempy As Integer
tempy = y
Dim CustName As String = Trim(Reader("firstname")) & " " & Trim(Reader("lastname"))
CustName = StrConv(CustName, VbStrConv.ProperCase)
e.Graphics.DrawString(CustName, myfont, Brushes.Black, e.MarginBounds.X, y)
y += CInt(myfont.GetHeight(e.Graphics))
Dim street As String = ""
If Trim(Reader("street2").ToString) <> "" And Not (IsDBNull(Reader("street2"))) Then
street += Trim(Reader("street1").ToString) & vbCrLf & Trim(Reader("street2"))
Else
street += Trim(Reader("street1").ToString)
End If
street = StrConv(street, VbStrConv.ProperCase)
e.Graphics.DrawString(street, myfont, Brushes.Black, e.MarginBounds.X, y)
y += CInt(myfont.GetHeight(e.Graphics))
Dim CityStateZip As String = ""
CityStateZip = StrConv(Trim(Reader("city")), VbStrConv.ProperCase) & ", " & Trim(Reader("state")) & ", " & Reader("zipcode")
e.Graphics.DrawString(CityStateZip, myfont, Brushes.Black, e.MarginBounds.X, y)
x += 200
e.Graphics.DrawString(Trim(Reader("phonenum")), myfont, Brushes.Black, x, tempy)
tempy += CInt(myfont.GetHeight(e.Graphics))
y += CInt(2 * myfont.GetHeight(e.Graphics))
e.Graphics.DrawString(Trim(Reader("emailaddress")), myfont, Brushes.Black, x, tempy)
x = e.MarginBounds.X
'If intPrintLineCount1 > intLinesPerPage Then
' e.HasMorePages = True
' intPrintLineCount1 = 0
'Else
' e.HasMorePages = False
'End If
If y + myfont.Height > e.MarginBounds.Bottom Then
e.HasMorePages = True
End If
'intPrintLineCount1 += 10
End While
Cmd.Dispose()
Next
Reader.Close()
Conn.Close()
Conn.Dispose()
End Sub