我正在尝试在VB.net(2012)中打开打印预览对话框。我知道如何打开打印预览对话框,以及如何在文档中添加内容。
我的问题是,如何在文档中打印表格?
目前我在互联网上找到的所有指南都没有帮助。
我目前的代码:
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles Document.PrintPage
Dim text As String = strTable
Dim printFont As New System.Drawing.Font("Arial", 16, System.Drawing.FontStyle.Regular)
e.Graphics.DrawString(text, printFont, System.Drawing.Brushes.Black, 0, 0)
End Sub
答案 0 :(得分:1)
手动设置列并遍历行。
对于此示例,假设strTable包含一个字符串,其中的制表符分隔每列,并且回车符,换行符分隔行。您可以将字符串解析为行和列,然后放置它们
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
Handles PrintDocument1.PrintPage
#this is an example string I used to test the routine.
Dim strTable = "1 Col one" & vbTab & "col two" & vbTab & "col three" & vbCrLf &
"2 Col one" & vbTab & "col two" & vbTab & "col three" & vbCrLf &
"3 Col one" & vbTab & "col two" & vbTab & "col three" & vbCrLf
#This creates a string array containing each row of our table
Dim Rows() As String = Split(strTable, vbCrLf)
#this will keep track of our vertical position on the paper
Dim Row_Position As Single = 0
#This is where each column will be on the page, horizontally
Dim Column_Positions() As Single = {0, 100, 200}
Dim printFont As New System.Drawing.Font("Arial", 16, _
System.Drawing.FontStyle.Regular)
'Get the height of a row. I'm taking the height of a 'W' and adding a bit.
#Measurestring returns a Double which needs to be converted to single
Dim RowHeight As Single = CType(e.Graphics.MeasureString("W", printFont).Height * 1.25, Single)
For Each aRow In Rows
#Now, we split our row up into columns
Dim cols() As String = Split(aRow, vbTab)
#and just iterate through the columns, putting them where they need to be
For idx = 0 To cols.Length - 1
e.Graphics.DrawString(cols(idx), printFont, _
System.Drawing.Brushes.Black, _
e.MarginBounds.Left + Column_Positions(idx), _
e.MarginBounds.Top + Row_Position)
Next
Row_Position += RowHeight
Next
End Sub