Print multiple pages - vb.net

I'm converting from VB5 and am trying to get the equivalent of printer.NewPage in VB.NET.
My code is given below, but it simply prints the two lines on a single page.
The program prints two pages of calculated results (arrays etc), it is not reading and printing a file.
How do I get a second page?
Private Sub PrintGeneralReport()
Dim PrintPreviewSelected As Boolean = True
'Set the doc to print
Dim pDoc As New PrintDocument
pDoc.PrintController = New StandardPrintController 'turns off the printing page x of y dialog
'Get the printer to use
If Me.PrintDialog1.ShowDialog() = DialogResult.OK Then
pDoc.PrinterSettings.PrinterName = Me.PrintDialog1.PrinterSettings.PrinterName
'pDoc.DefaultPageSettings.Margins = New Margins(75, 50, 50, 50)
pDoc.DefaultPageSettings.Margins = New Margins(40, 10, 10, 10)
pDoc.OriginAtMargins = True
Else
pDoc = Nothing
Exit Sub
End If
' Install the PrintPage event handler.
AddHandler pDoc.PrintPage, AddressOf PrintGenReport
If PrintPreviewSelected Then
''print preview
PrintPreviewDialog1.Document = pDoc
PrintPreviewDialog1.UseAntiAlias = True
PrintPreviewDialog1.WindowState = FormWindowState.Maximized
PrintPreviewDialog1.ShowDialog()
Else
'just print
pDoc.Print()
End If
RemoveHandler pDoc.PrintPage, AddressOf PrintGenReport
End Sub
Private Sub PrintGenReport(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim fnt10 As Font = New Font("Courier New", 10, FontStyle.Regular)
e.Graphics.DrawString("Page 1", fnt10, Brushes.Black, 20, 100)
'ROARK1.Print_GeneralReportRK(Me, e)
e.HasMorePages = True
e.Graphics.DrawString("Page 2", fnt10, Brushes.Black, 20, 200)
'ROARK1.Print_MemberActions(e)
e.HasMorePages = False
End Sub

Try this:
Private PageNum As Integer = 1
Private Sub PrintGenReport(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim fnt10 As Font = New Font("Courier New", 10, FontStyle.Regular)
e.Graphics.DrawString("Page " & PageNum.ToString(), fnt10, Brushes.Black, 20, 100 * PageNum)
e.HasMorePages = (PageNum < 2)
PageNum += 1
End Sub
Note the PageNum variable is defined at the class level. You should also add a line to the PrintGeneralReport() method to set it back to 1 at the beginning of each print job.

Related

Print a Cheque with PrintDocument in VB.NET

I am using following code in VB.NET 4.0 to print a cheque.
In printpreview dialog, print is shown correctly but when printed actually,
print starts from bottom of cheque.
I want print to start from start point of cheque.
Cheque is inserted in middle of printer tray vertically.
Private print_document As PrintDocument
Private FIRST_TO_PRINT As String = "CHEQUE"
Private fontsize As Integer = 12
Private _ID As Integer = 0
Private CHEQUE_DATE As Date
Private CLIENT_NAME As String
Private CLIENT_NAME_ON_CHEQUE As String
Private AMOUNT As Decimal
Private AMOUNT_IN_WORDS As String
Public Sub New(ID As Integer)
_ID = ID
End Sub
Public Function PreparePrintDocument() As PrintDocument
' Make the PrintDocument object.
print_document = New PrintDocument
print_document.DefaultPageSettings.PaperSize = New PaperSize("Custom", 336, 768)
'print_document.OriginAtMargins = True
'print_document.DefaultPageSettings.Margins.Left = 200
'print_document.DefaultPageSettings.Margins.Right = 10
'print_document.DefaultPageSettings.Margins.Bottom = 10
'print_document.DefaultPageSettings.Margins.Top = 200
AddHandler print_document.BeginPrint, AddressOf Print_BeginPrint
' Install the PrintPage event handler.
AddHandler print_document.PrintPage, AddressOf Print_PrintPage
' Return the object.
Return print_document
End Function
Protected Sub Print_BeginPrint(sender As Object, e As PrintEventArgs)
GetVoucherDetails()
End Sub
Private Sub GetVoucherDetails()
Dim objVOUCHER_BLL As VOUCHER_BLL
Try
objVOUCHER_BLL = New VOUCHER_BLL
Dim temps As VOUCHERDataTable = objVOUCHER_BLL.GetVoucherByID(_ID)
If temps.Count > 0 Then
Dim temp As VOUCHERRow = temps(0)
CHEQUE_DATE = temp.CHEQUE_DATE
CLIENT_NAME = temp.CLIENT_NAME
CLIENT_NAME_ON_CHEQUE = temp.CLIENT_NAME_ON_CHEQUE
AMOUNT = temp.AMOUNT
AMOUNT_IN_WORDS = numToWords.AmtInWord(temp.AMOUNT)
End If
Catch ex As Exception
Finally
objVOUCHER_BLL = Nothing
End Try
End Sub
' Print the next page.
Private Sub Print_PrintPage(ByVal sender As Object, ByVal e _
As System.Drawing.Printing.PrintPageEventArgs)
Dim our_brush As Brush = Brushes.Black
Dim font As New Font("Verdana", fontsize)
If FIRST_TO_PRINT = "CHEQUE" Then
e.PageSettings.PaperSize = New PaperSize("Custom", 336, 768)
e.Graphics.ResetTransform()
e.Graphics.TranslateTransform(306, 580)
e.Graphics.RotateTransform(90)
e.Graphics.DrawString(CHEQUE_DATE.ToString("dd MM yyyy"), font, our_brush, New Point(0, 0))
e.Graphics.ResetTransform()
e.Graphics.TranslateTransform(262, 20)
e.Graphics.RotateTransform(90)
e.Graphics.DrawString(CLIENT_NAME_ON_CHEQUE, font, our_brush, New Point(70, 0))
e.Graphics.ResetTransform()
e.Graphics.TranslateTransform(232, 140)
e.Graphics.RotateTransform(90)
e.Graphics.DrawString(AMOUNT_IN_WORDS.Replace("Rupees ", String.Empty).ToUpper, font, our_brush, New Point(0, 0))
e.Graphics.ResetTransform()
e.Graphics.TranslateTransform(206, 600)
e.Graphics.RotateTransform(90)
e.Graphics.DrawString(AMOUNT.ToString("F2") & " /-", font, our_brush, New Point(0, 0))
' e.HasMorePages = True
' e.Graphics.ResetTransform()
' FIRST_TO_PRINT = "VOUCHER"
'Else
' e.PageSettings.PaperSize = New PaperSize("Custom", 612, 792)
' e.Graphics.DrawString("VOUCHER", font, our_brush, New Point(200, 200))
' FIRST_TO_PRINT = "CHEQUE"
e.Graphics.ResetTransform()
e.HasMorePages = False
End If
End Sub

VB.Net Process.CloseMainWindow and Process.Close not working

I've used a background worker to launch an application, wait for cancellation and then close the application. But for some reason the application never closes. I've tried with and without notificationPreview.WaitForExit()
Private Sub bgWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
'Extract the executable to the applications directory path and execute it
Dim notificationPreview As New Process
Dim monitorExe As Byte() = My.Resources.ITSupportMonitoring
My.Computer.FileSystem.WriteAllBytes(My.Application.Info.DirectoryPath & "ITSupportMonitoring.exe", monitorExe, False)
notificationPreview = Process.Start(My.Application.Info.DirectoryPath & "ITSupportMonitoring.exe")
notificationPreview.WaitForInputIdle()
'Wait until the worker is sent a cancellation request
Do Until bgWorker.CancellationPending = True
System.Threading.Thread.Sleep(500)
Loop
'If the process hasn't been closed by the user close it
If Not notificationPreview.HasExited Then 'If the process is still running
notificationPreview.CloseMainWindow() 'Tell the main window of the notification process to close
notificationPreview.WaitForExit()
notificationPreview.Close() 'Free all resources used by the notification process
End If
My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "ITSupportMonitoring.exe") 'Delete the executable file
e.Cancel = True
End Sub
Here is the FULL code for the process which will not close:
Public Class frmMonitoring
Dim noticeText As String
Private Sub frmMonitoring_Load(sender As Object, e As EventArgs) Handles Me.Load
'Set the notice text
If My.Application.CommandLineArgs.Count > 0 Then
noticeText = My.Application.CommandLineArgs(0)
Else
noticeText = "Example String"
End If
Me.ForeColor = Color.Black
tmrFlash.Interval = 1000
tmrFlash.Start()
Me.Top = 0
Me.Left = 0
Me.TopMost = True
End Sub
Private Sub tmrFlash_Tick(sender As Object, e As EventArgs) Handles tmrFlash.Tick
If Me.ForeColor = Color.Black Then
Me.ForeColor = Color.Red
Else
Me.ForeColor = Color.Black
End If
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
MyBase.OnPaint(e)
Dim drawFont As New System.Drawing.Font(SystemFonts.DefaultFont.Name, 16)
Dim drawBrush As New System.Drawing.SolidBrush(Me.ForeColor)
Dim drawFormat As New System.Drawing.StringFormat
Dim drawRect As New RectangleF(e.ClipRectangle.Location, e.ClipRectangle.Size)
drawRect.Height = drawRect.Height * 0.65 'The bottom line of text was getting partially clipped, so reduced the height of the drawing area to 65%
drawFont = GetAdjustedFont(e.Graphics, noticeText, drawFont, drawRect, 40, 4, True)
Dim stringFormat As New StringFormat(StringFormatFlags.NoClip)
stringFormat.Alignment = StringAlignment.Center
stringFormat.LineAlignment = StringAlignment.Center
e.Graphics.DrawString(noticeText, drawFont, drawBrush, RectangleF.op_Implicit(ClientRectangle), stringFormat)
drawFont.Dispose()
drawBrush.Dispose()
End Sub
Public Function GetAdjustedFont(ByRef GraphicRef As Graphics, ByVal GraphicString As String, ByVal OriginalFont As Font, ByVal ContainerSize As RectangleF, ByVal MaxFontSize As Integer, ByVal MinFontSize As Integer, ByVal SmallestOnFail As Boolean) As Font
'Loop through font sizes and MeasureString to find the largest font which can be used
For AdjustedSize As Integer = MaxFontSize To MinFontSize Step -1
Dim TestFont = New Font(OriginalFont.Name, AdjustedSize, OriginalFont.Style)
Dim charsFitted As Integer
Dim linesFilled As Integer
' Test the string with the new size
Dim AdjustedSizeNew = GraphicRef.MeasureString(GraphicString, TestFont, ContainerSize.Size, New StringFormat, charsFitted, linesFilled)
If charsFitted = GraphicString.Length Then 'If every characted in the string was printed
'Good font, return it
Return TestFont 'New Font(TestFont.Name, TestFont.Size - 1, TestFont.Style)
End If
Next
' If you get here there was no fontsize that worked
' return MinimumSize or Original?
If SmallestOnFail Then
Return New Font(OriginalFont.Name, MinFontSize, OriginalFont.Style)
Else
Return OriginalFont
End If
End Function
End Class

Loop through Dates vb.net

I want to create a datagridview every day. Here is my code so far. It's not displaying any errors but when I run the code it just load the form but the dgv does not appear. What can I do?
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim start As Date = Date.Now
Dim apocap As Date = Date.Parse(#8/22/2050#)
Dim loopdate As Date = start
While start < apocap
Dim dgv As New DataGridView
With dgv
.Size = New Size(250, 250)
.ColumnCount = 2
.RowCount = 12
.Location = New Point(12, 9)
.Visible = True
End With
start = start.Date.AddDays(1)
End While
End Sub
End Class
You have to add them to your form. Additionally, you'll want to change the .Left and/or .Top (.Location) properties so they don't all stack on top of each other:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim start As DateTime = DateTime.Today
Dim apocap As New DateTime(2050, 8, 22)
Dim i As Integer = 0
While start < apocap
Dim dgv As New DataGridView
With dgv
.Size = New Size(250, 250)
.ColumnCount = 2
.RowCount = 12
.Location = New Point(12, (9 + (250 * i)))
.Visible = True
End With
Me.Controls.Add(dgv)
i += 1
start = start.AddDays(1)
End While
End Sub
For fun, I like to write it like this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim start As DateTime = DateTime.Today
Dim apocap As New DateTime(2050, 8, 22)
Dim count As Integer = CInt((apocap - start).TotalDays)
Me.Controls.AddRange(Enumerable.Range(0, count).Select(
Function(i)
Return New DataGridView With {
.Size = New Size(250, 250),
.ColumnCount = 21,
.RowCount = 12,
.Location = New Point(12, (9 + (250 * i))),
.Visible = True
}
'start.AddDays(i) is there if you need it
End Function
).ToArray())
End Sub

Printing multiple pages from an ArrayList

First let me start off with I am not a vb.net developer. In fact I have never been trained in the art of VB. That being said I am working on a very simple application that takes a csv file and parses a single column to an array list. Now i need to take that array list and print a individual page (Without preview) of each item on the array list. So each item on the array list will have its own page.
Heres what i have so far. Im sure Im way off seeing as I cant figure out how to turn this into multi-pages.
Private Sub Print()
Dim PrintPreviewSelected As Boolean = False
'Set the doc to print
Dim pDoc As New PrintDocument
pDoc.PrintController = New StandardPrintController 'turns off the printing page x of y dialog
Try
Using sr As New StreamReader(file)
defPrinter = sr.ReadToEnd()
End Using
Catch e As Exception
End Try
If defPrinter = "" Then
If Me.PrintDialog1.ShowDialog() = DialogResult.OK Then
pDoc.PrinterSettings.PrinterName = Me.PrintDialog1.PrinterSettings.PrinterName
End If
Else
pDoc.PrinterSettings.PrinterName = defPrinter
End If
pDoc.DefaultPageSettings.Landscape = True
pDoc.DefaultPageSettings.Margins = New Margins(40, 10, 10, 10)
pDoc.OriginAtMargins = True
AddHandler pDoc.PrintPage, AddressOf PrintSett
If PrintPreviewSelected Then
PrintPreviewDialog1.Document = pDoc
PrintPreviewDialog1.UseAntiAlias = True
PrintPreviewDialog1.WindowState = FormWindowState.Maximized
PrintPreviewDialog1.ShowDialog()
Else
If txtFile.Text <> "" Then
pDoc.Print()
Else
MessageBox.Show("You must select a file first", "Select a file.")
End If
End If
RemoveHandler pDoc.PrintPage, AddressOf PrintSett
End Sub
Private Sub PrintSett(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim fnt10 As Font = New Font("Courier New", 34, FontStyle.Regular)
e.Graphics.DrawString("", fnt10, Brushes.Black, 318, 412)
End Sub
Any help would be appreciated! I know i havent laid any of the foundation for you guys to work off of but frankly Im strait up lost. Thanks guys!
Following matzone's suggestion I was able to figure it out.
Dim PageNumber As Integer = 1
Dim morePage As String
Private Sub PrintSett(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim ReportFont As New Font("Arial", 45, FontStyle.Regular)
Dim VerticalPrintLocationSingle As Single = 412
Dim HorizontalPrintLocationSingle As Single = e.MarginBounds.Left
Dim TextString As String
Dim sngCenterPage As Single
If customerList.Count > (PageNumber) Then
If customerList.Item(PageNumber) IsNot "" Then
TextString = customerList.Item(PageNumber)
Console.WriteLine(customerList.Item(PageNumber))
sngCenterPage = Convert.ToSingle(e.PageBounds.Width / 2 - e.Graphics.MeasureString(customerList.Item(PageNumber), ReportFont).Width / 2)
PageNumber += 1
morePage = True
End If
Else
morePage = False
customerList.Clear()
End If
e.Graphics.DrawString(TextString, ReportFont, Brushes.Black, sngCenterPage, VerticalPrintLocationSingle)
e.HasMorePages = morePage
End Sub
Thanks again!

WMPlayer doesn't start

I'm trying to get a number of frames from video using windows media player control. It was placed on Panel control.
Public Class Form1
Private b As New System.Drawing.Bitmap(160, 120)
Private rct As New Rectangle(0, 0, 160, 120)
Private pb As PictureBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
wm.URL = TextBox1.Text
wm.Ctlcontrols.play()
End Sub
Private Sub wm_OpenStateChange(sender As Object, e As AxWMPLib._WMPOCXEvents_OpenStateChangeEvent) Handles wm.OpenStateChange
If e.newState = 13 And wm.playState = 3 Then
Dim g As Graphics = Graphics.FromImage(b)
g.CopyFromScreen(PointToScreen(Panel1.Location), New Drawing.Point(0, 0), b.Size, CopyPixelOperation.SourceCopy)
pb = New PictureBox With {.Width = 160, .Height = 120, .Image = b}
FlowLayoutPanel1.Controls.Add(pb)
Try
While True
wm.Ctlcontrols.currentPosition += 20
Application.DoEvents()
If wm.Ctlcontrols.currentPosition > wm.currentMedia.duration - 20 Then
Exit Sub
End If
b = New Bitmap(160, 120)
g = Graphics.FromImage(b)
g.CopyFromScreen(PointToScreen(Panel1.Location), New Drawing.Point(0, 0), b.Size, CopyPixelOperation.SourceCopy)
pb = New PictureBox With {.Width = 160, .Height = 120, .Image = b}
FlowLayoutPanel1.Controls.Add(pb)
End While
Catch ex As Exception
End Try
End If
End Sub
End Class
As a result I want to get a number of frames in FlowLayoutPanel Control. But there are some 'Black Boxes' (repeated first frame). Any ideas?.. How can I make WMP to Update it's position and layout? My imagine is over.