I have a large VB programme that prints many documents mainly from DataGridViews..
I would also like the option to create PDF's.
Looking around the web I always get pointed to here.
I was hoping that someone may be able to help me convert my Print Document code to a PDFSharp document.
The main problem is the number of pages and amount of data may vary.
Here is a form that will Generate a Table from a DataGridView and send it to PrintPreview.
Simply add a Datagridview, Button, PrintPriviewDialog and PrintDocument to a new form and paste the code.
Code:
Imports System.IO
Imports System.Diagnostics
Imports System.Drawing
Public Class Form1
Dim mRow As Integer = 0
Dim newpage As Boolean = True
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
With DataGridView1
Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
fmt.LineAlignment = StringAlignment.Center
fmt.Trimming = StringTrimming.EllipsisCharacter
'define header room
Dim y As Single = 250
Do While mRow < .RowCount
Dim row As DataGridViewRow = .Rows(mRow)
Dim x As Single = e.MarginBounds.Left
Dim h As Single = 0
For Each cell As DataGridViewCell In row.Cells
Dim rc As RectangleF = New RectangleF(x, y, cell.Size.Width, cell.Size.Height)
e.Graphics.DrawRectangle(Pens.Black, rc.Left, rc.Top, rc.Width, rc.Height)
If (newpage) Then
' Header and footer go in here
e.Graphics.DrawString(DataGridView1.Columns(cell.ColumnIndex).HeaderText, .Font, Brushes.Black, rc, fmt)
Else
' DataGridView Loop
e.Graphics.DrawString(DataGridView1.Rows(cell.RowIndex).Cells(cell.ColumnIndex).FormattedValue.ToString(), .Font, Brushes.Black, rc, fmt)
End If
x += rc.Width
h = Math.Max(h, rc.Height)
Next
'define footer room and if new page is required
newpage = False
y += h
mRow += 1
If y + h > 600 Then
e.HasMorePages = True
mRow -= 1
newpage = True
Exit Sub
End If
Loop
mRow = 0
End With
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Populate DataGridView
Dim dt As New DataTable
dt.Columns.Add("Number", GetType(Integer))
dt.Columns.Add("name", GetType(String))
dt.Columns.Add("address", GetType(String))
For i As Integer = 0 To 100
dt.Rows.Add(i, "Name " & i.ToString, "Address " + i.ToString)
Next
DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
End Class