How to print multiple page using e.HasMorePages? - vb.net

I want to print data from datagridview,
however when data exceed than one page it is missing. I try to use e.HasMorePages to print multiple pages. I try and search for example for 3 hours ago but unfortunately it does not work
Now when I click print, It is print only the same page without stopping.
Please help.
Private Sub PrintColorConsumption_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintColorConsumption.PrintPage
Dim x As Integer = 100
Dim y As Integer = 25
Dim header As Boolean = True
'draw headers
Dim j As Integer = 0
Do While (j < Me.DataGridView3.Columns.Count)
Dim rect As Rectangle = New Rectangle(x, y, Me.DataGridView3.Columns(j).Width, Me.DataGridView3.ColumnHeadersHeight)
Dim sf As StringFormat = New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
e.Graphics.FillRectangle(Brushes.LightGray, rect)
e.Graphics.DrawRectangle(Pens.Black, rect)
If (Not (Me.DataGridView3.Columns(j).HeaderText) Is Nothing) Then
e.Graphics.DrawString(Me.DataGridView3.Columns(j).HeaderText, SystemFonts.DefaultFont, Brushes.Black, rect, sf)
End If
x = (x + rect.Width)
j = (j + 1)
Loop
x = 100
y = (y + Me.DataGridView3.ColumnHeadersHeight)
'draw rows
For Each row As DataGridViewRow In Me.DataGridView3.Rows
j = 0
Do While (j < Me.DataGridView3.Columns.Count)
Dim cell As DataGridViewCell
cell = row.Cells(j)
Dim rect As Rectangle = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)
Dim sf As StringFormat = New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
e.Graphics.DrawRectangle(Pens.Black, rect)
If (Not (cell.Value) Is Nothing) Then
e.Graphics.DrawString(cell.Value.ToString, SystemFonts.DefaultFont, Brushes.Black, rect, sf)
End If
x = (x + rect.Width)
j = (j + 1)
Loop
x = 100
y = (y + row.Height)
'----------------------New page----------------------------
If (y > e.MarginBounds.Bottom) Then 'Print new page
e.HasMorePages = True
y = 20
End If
'-----------------------------------------------------------------
Next
End Sub

Printing requires you to maintain where you are within the data that you are printing for every PrintPage event. The way you have your variables declared they go out of scope and are set to their initial values every time the event is raised.
See if the following code, which wasn't tested, helps. Note that a variable was declared outside of the event handler to keep track of the current row.
Dim whRow As Integer = 0
Private Sub PrintColorConsumption_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintColorConsumption.PrintPage
Dim x As Integer = 100
Dim y As Integer = 25
Dim header As Boolean = True
'draw headers
Dim j As Integer = 0
Do While (j < Me.DataGridView3.Columns.Count)
Dim rect As Rectangle = New Rectangle(x, y, Me.DataGridView3.Columns(j).Width, Me.DataGridView3.ColumnHeadersHeight)
Dim sf As StringFormat = New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
e.Graphics.FillRectangle(Brushes.LightGray, rect)
e.Graphics.DrawRectangle(Pens.Black, rect)
If (Not (Me.DataGridView3.Columns(j).HeaderText) Is Nothing) Then
e.Graphics.DrawString(Me.DataGridView3.Columns(j).HeaderText, SystemFonts.DefaultFont, Brushes.Black, rect, sf)
End If
x = (x + rect.Width)
j = (j + 1)
Loop
x = 100
y = (y + Me.DataGridView3.ColumnHeadersHeight)
'draw rows
For whRow = whRow To Me.DataGridView3.RowCount - 1
Dim drow As DataGridViewRow = Me.DataGridView3.Rows(whRow)
j = 0
Do While (j < Me.DataGridView3.Columns.Count)
Dim cell As DataGridViewCell
cell = drow.Cells(j)
Dim rect As Rectangle = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)
Dim sf As StringFormat = New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
e.Graphics.DrawRectangle(Pens.Black, rect)
If (Not (cell.Value) Is Nothing) Then
e.Graphics.DrawString(cell.Value.ToString, SystemFonts.DefaultFont, Brushes.Black, rect, sf)
End If
x = (x + rect.Width)
j = (j + 1)
Loop
x = 100
y = (y + drow.Height)
'----------------------New page----------------------------
If (y > e.MarginBounds.Bottom) Then 'Print new page
e.HasMorePages = True
y = 20
End If
'-----------------------------------------------------------------
Next
End Sub

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 change in Datagridview alignment of a specific Column for printing?

I apologize for my weird code. I'm a complete newbie and just learning how stuff works.
I found this code and changed some stuff to it.
My problem is:
I somehow managed for all columns the alignment to be right but I need for my first Colum "Data1" the alignment to be left. I can change that in the settings or with a click of a button but when printing it's just right aligned with the others.. I have tried everything but my knowledge is maybe 2% so I would really appreciate the help.
I have a Button1, DataGridView1, PrintPreviewDialog1, PrintDocument1, PrintDialog1
Here is a picture of the Form and an example of Print-Preview:
https://drive.google.com/file/d/1VnUzrM9fgiEcJExrXalo7Uo6XKQwT3Sd/view?usp=sharing
This is my Code:
Private mRow As Integer = 0
Private newpage As Boolean = True
Private m_PagesPrinted As Integer = 1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With DataGridView1
.Rows.Add("Plan 1", "50", "2,99", "28,40", "170,90")
.Rows.Add("Plan 27 a", "80", "14,99", "227,85", "1427,05")
.Rows.Add("Plan 27 b", "808", "47,45", "84,85", "14,05")
.Rows.Add("Plan 27 c", "80", "12,21", "77,10", "27,05")
.Rows.Add("Plan 27 d", "470", "14,50", "15,40", "227,99")
.Rows.Add("Plan 27 e", "2", "99,00", "2,84", "4427,67")
.Rows.Add("Plan 27 f", "4", "10,00", "9,48", "7,74")
.Rows.Add("Plan 27 g", "54", "150,50", "46,64", "127,50")
End With
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
newpage = True
'Dim frm As Form = DirectCast(PrintPreviewDialog1, Form)
PrintPreviewDialog1.PrintPreviewControl.StartPage = 0
PrintPreviewDialog1.PrintPreviewControl.Zoom = 0.8
PrintPreviewDialog1.WindowState = FormWindowState.Maximized
' sets it to show '...' for long text
Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
fmt.LineAlignment = StringAlignment.Center
Dim newfmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
newfmt.LineAlignment = StringAlignment.Near
'fmt.Trimming = StringTrimming.EllipsisCharacter
Dim y2 As Int32 = 200
Dim rc As Rectangle
Dim x2 As Int32 = 2
Dim h As Int32 = 200
Dim row2 As DataGridViewRow
' print the header text for a new page
' use a grey bg just like the control
If newpage Then
row2 = DataGridView1.Rows(mRow)
x2 = e.MarginBounds.Left
For Each cell As DataGridViewCell In row2.Cells
Dim x As Integer = 170
Dim y As Integer = 360
Dim xwidth As Integer = 190
Dim yheight As Integer = 20
Dim cellwidth As Integer = 300
Dim cellheight As Integer = 370
Dim fon As New Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold)
Dim rect As New Rectangle(x, 100, xwidth, yheight)
''##########################################################################
''##########################################################################
Dim rek1 As New Rectangle(40, 350, 750, 20)
e.Graphics.DrawRectangle(Pens.Black, rek1)
Dim rek2 As New Rectangle(40, 370, 750, 100)
e.Graphics.DrawRectangle(Pens.Black, rek2)
''##########################################################################
''##########################################################################
e.Graphics.DrawString("Data1 Data2 Data3 Data4 Data5", fon, Brushes.Black, 42, 351)
Next
y2 += h
End If
newpage = False
' now print the data for each row
Dim thisNDX As Int32
For thisNDX = mRow To DataGridView1.RowCount - 1
' no need to try to print the new row
If DataGridView1.Rows(thisNDX).IsNewRow Then Exit For
row2 = DataGridView1.Rows(thisNDX)
x2 = e.MarginBounds.Left
h = 0
' reset X for data
x2 = e.MarginBounds.Left
' print the data
For Each cell As DataGridViewCell In row2.Cells
If cell.Visible Then
rc = New Rectangle(x2 - 20, y2, cell.Size.Width, cell.Size.Height)
Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
Case DataGridViewContentAlignment.BottomRight,
DataGridViewContentAlignment.BottomRight
fmt.Alignment = StringAlignment.Far
rc.Offset(-170, -30)
Case DataGridViewContentAlignment.BottomRight,
DataGridViewContentAlignment.BottomRight
fmt.Alignment = StringAlignment.Far
Case Else
fmt.Alignment = StringAlignment.Far
rc.Offset(-170, -30)
End Select
e.Graphics.DrawString(cell.FormattedValue.ToString(), DataGridView1.Font, Brushes.Black, rc, fmt)
x2 += rc.Width
h = Math.Max(h, rc.Height)
End If
Next
y2 += h
' next row to print
mRow = thisNDX + 1
If y2 + h > 500 Then
e.HasMorePages = True
mRow -= 1 'causes last row To rePrint On Next page
m_PagesPrinted += 1
newpage = True
Return
End If
Next
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
PrintDocument1.Print()
End If
End Sub
End Class
Can somebody explain me what needs to be changed so when printing then the first column is left aligned and the rest is on the right side..
Thanks in advance!!
Your Select Case doesn't make sense. Your first Case matches DataGridViewContentAlignment.BottomRight twice and then your second case matches the same value twice more. In all cases, you're setting the Alignment of your StringFormat to StringAlignment.Far. I would think that it should be more like this:
Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
Case DataGridViewContentAlignment.TopLeft,
DataGridViewContentAlignment.MiddleLeft,
DataGridViewContentAlignment.BottomLeft
fmt.Alignment = StringAlignment.Near
Case DataGridViewContentAlignment.TopCenter,
DataGridViewContentAlignment.MiddleCenter,
DataGridViewContentAlignment.BottomCenter
fmt.Alignment = StringAlignment.Center
Case DataGridViewContentAlignment.TopRight,
DataGridViewContentAlignment.MiddleRight,
DataGridViewContentAlignment.BottomRight
fmt.Alignment = StringAlignment.Far

Datagrid Columns Not Fitting Print Preview Page

i've been trying to print some records with more than 7 columns it is shown on the datagrid.but the columns are not fitting the page below are the screenshots
Below is how the datagridview to be printed looks like
Below is the code i used for the printdocument tool
Dim mRow As Integer = 0
Dim newpage As Boolean = True
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
' sets it to show '...' for long text
Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
fmt.LineAlignment = StringAlignment.Center
fmt.Trimming = StringTrimming.EllipsisCharacter
Dim y As Int32 = e.MarginBounds.Top
Dim rc As Rectangle
Dim x As Int32
Dim h As Int32 = 0
Dim row As DataGridViewRow
' print the header text for a new page
' use a grey bg just like the control
If newpage Then
row = datagrid1.Rows(mRow)
x = e.MarginBounds.Left
For Each cell As DataGridViewCell In row.Cells
' since we are printing the control's view,
' skip invidible columns
If cell.Visible Then
rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)
e.Graphics.FillRectangle(Brushes.LightGray, rc)
e.Graphics.DrawRectangle(Pens.Black, rc)
' reused in the data pront - should be a function
Select Case datagrid1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
Case DataGridViewContentAlignment.BottomRight,
DataGridViewContentAlignment.MiddleRight
fmt.Alignment = StringAlignment.Far
rc.Offset(-1, 0)
Case DataGridViewContentAlignment.BottomCenter,
DataGridViewContentAlignment.MiddleCenter
fmt.Alignment = StringAlignment.Center
Case Else
fmt.Alignment = StringAlignment.Near
rc.Offset(2, 0)
End Select
e.Graphics.DrawString(datagrid1.Columns(cell.ColumnIndex).HeaderText, datagrid1.Font, Brushes.Black, rc, fmt)
x += rc.Width
h = Math.Max(h, rc.Height)
End If
Next
y += h
End If
newpage = False
' now print the data for each row
Dim thisNDX As Int32
For thisNDX = mRow To datagrid1.RowCount - 1
' no need to try to print the new row
If datagrid1.Rows(thisNDX).IsNewRow Then Exit For
row = datagrid1.Rows(thisNDX)
x = e.MarginBounds.Left
h = 0
' reset X for data
x = e.MarginBounds.Left
' print the data
For Each cell As DataGridViewCell In row.Cells
If cell.Visible Then
rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)
' SAMPLE CODE: How To
' up a RowPrePaint rule
'If Convert.ToDecimal(row.Cells(5).Value) < 9.99 Then
' Using br As New SolidBrush(Color.MistyRose)
' e.Graphics.FillRectangle(br, rc)
' End Using
'End If
e.Graphics.DrawRectangle(Pens.Black, rc)
Select Case datagrid1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
Case DataGridViewContentAlignment.BottomRight,
DataGridViewContentAlignment.MiddleRight
fmt.Alignment = StringAlignment.Far
rc.Offset(-1, 0)
Case DataGridViewContentAlignment.BottomCenter,
DataGridViewContentAlignment.MiddleCenter
fmt.Alignment = StringAlignment.Center
Case Else
fmt.Alignment = StringAlignment.Near
rc.Offset(2, 0)
End Select
e.Graphics.DrawString(cell.FormattedValue.ToString(),
datagrid1.Font, Brushes.Black, rc, fmt)
x += rc.Width
h = Math.Max(h, rc.Height)
End If
Next
y += h
' next row to print
mRow = thisNDX + 1
If y + h > e.MarginBounds.Bottom Then
e.HasMorePages = True
' mRow -= 1 causes last row to rePrint on next page
newpage = True
Return
End If
Next
End Sub
this is the code for the print button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub

how to create jpg file from given string

I have converted given string to JPG file format. But i need those image string in center. Iam getting output from leftside of rectangle.
Dim stext As String = "Testing"
Dim format As StringFormat = New StringFormat()
Dim MyRect As Rectangle = New Rectangle(0, 0, 400, 800)
Dim MyGraphics As Graphics = Me.CreateGraphics()
Dim MyImg As Image = New Bitmap(391, 132, MyGraphics)
Dim imageGraphics As Graphics = Graphics.FromImage(MyImg)
imageGraphics.FillRectangle(Brushes.White, MyRect)
format.Alignment = StringAlignment.Center
format.LineAli`enter code here`gnment = StringAlignment.Center
imageGraphics.DrawString("Testing", New Font("Times New Roman", 30, Drawing.FontStyle.Bold), Brushes.Black, RectangleF.op_Implicit(MyRect))
MyGraphics.DrawImage(MyImg, MyRect)
MyImg.Save(Destfilename & "/" & "test.jpg")
I have given this code output. But i need this string to in center position. How to do, Kindly help me through.
Output: https://drive.google.com/file/d/0B_nzYHWVJJ7Ka3N0V2NmRnl3UFk/view?usp=sharing
I hope this example could help you
Private Sub CenterTextAt(ByVal gr As Graphics, ByVal txt As _
String, ByVal x As Single, ByVal y As Single)
' Mark the center for debugging.
gr.DrawLine(Pens.Red, x - 10, y, x + 10, y)
gr.DrawLine(Pens.Red, x, y - 10, x, y + 10)
' Make a StringFormat object that centers.
Dim sf As New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
' Draw the text.
gr.DrawString(txt, Me.Font, Brushes.Black, x, y, sf)
sf.Dispose()
End Sub