下面的代码可以很好地打印图像和文本。
现在的问题是,当页面被填满时,我如何自动将打印移动到下一页。
添加一个页码也很好:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
PrintDocument1.Print()
End Sub
Private Sub printDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim rect1 As Rectangle = New Rectangle(New Point(0, 0), PictureBox1.Image.Size)
Dim rect2 As Rectangle = New Rectangle(New Point(100, 200), PictureBox1.Image.Size)
Dim fmt As StringFormat = New StringFormat()
e.Graphics.DrawImage(PictureBox1.Image, rect1)
e.Graphics.DrawString(RichTextBox1.Text, RichTextBox1.Font, New SolidBrush(Color.Red), rect2, fmt)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For S = 1 To 200
RichTextBox1.AppendText("Test Line No. - " & S & vbCrLf)
Next
End Sub
End Class
发布于 2014-03-18 10:53:06
PrintPageEventArgs
包含一个成员HasMorePages
,您可以将其设置为True,以便在当前迭代结束时再次引发相同的事件。
要打印页码,您需要保留一个本地类变量来跟踪当前页码。然后使用e.Graphics.DrawString()
重载在页面上的任意位置打印页码。
使用您自己的代码的示例:
Private mPageNumber As Integer = 1
Private Sub printDocument1_PrintPage(ByVal sender As System.Object, ByVal e As _
System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim rect1 As Rectangle = New Rectangle(New Point(0, 0), PictureBox1.Image.Size)
Dim rect2 As Rectangle = New Rectangle(New Point(100, 200), PictureBox1.Image.Size)
Dim fmt As StringFormat = New StringFormat()
e.Graphics.DrawImage(PictureBox1.Image, rect1)
e.Graphics.DrawString(RichTextBox1.Text, RichTextBox1.Font, New SolidBrush(Color.Red), rect2, fmt)
Using f as New Font("Arial" , 10)
e.Graphics.DrawString(mPageNumber.ToString(), , Brushes.Black, 0, 0) 'Page number at top-left of the page
End Using
mPageNumber += 1
e.HasMorePages = (mPageNumber <= 10) 'Will keep printing till 10 pages are printed
End Sub
转到下一页完全取决于您希望如何计算下一页。具体地说,您将需要以其自己的字体打印每个字符(因为它是一个RichTextBox
),然后还要处理段落等。如果这还不够,您可能还需要处理双向文本、文本换行、对齐等等。欢迎来到印刷世界!!
我不会在这里编写确切的代码,但会给你一些提示,以便你可以开始你的旅程。RichTextBox
有一个名为GetPositionFromCharIndex()
的方法,它为您提供指定字符索引的x,y坐标。您可以在PrintPage
事件处理程序中使用循环来确定Y坐标小于或等于e.MarginBounds.Height
的最后一个字符,然后将所有单词向上发送到索引到DrawString()
函数。您应该保留一个类级别变量来跟踪当前页面上打印到的最后一个字符,然后在下一次迭代中从该点开始。您可以使用以布局矩形为参数的DrawString()
重载,并将e.MarginBounds
发送给它,让它自动为您执行自动换行。
请记住,这只适用于所有文本都使用单一字体的RichTextBox,考虑到RichTextBox的用途,这是非常不可能的。对于有多种字体的情况,您需要为由单个字体组成的每个字符范围多次调用DrawString()
。正如我所说的,这有许多细节(如字体字距调整、悬边和其他问题)不能在这里讨论。继续阅读,你会在SO和其他地方找到很多好东西。
https://stackoverflow.com/questions/22469493
复制相似问题