Automatic Printing vs basic 2013

Category: visual studio vb

Question

KonstantinaM on Wed, 26 Mar 2014 18:28:45


Hi all,

I am wondering if someone knows the code for printing a .txt file automatically.

I used code from the following page but it did not work (I was just printing blank pages).

http://msdn.microsoft.com/en-us/library/cwbe712d.aspx

Is there another way of doing it??

Thanks in advance for any help.

Konstantina.

Replies

Franklin Chen on Thu, 27 Mar 2014 07:01:49


Hi,

You need to handle PrintDocument.PrintPage event for printing multiple pages, here is a sample:

Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents printButton As System.Windows.Forms.Button
    Private printFont As Font
    Private streamToPrint As StreamReader

    Public Sub New()
        ' The Windows Forms Designer requires the following call.
        InitializeComponent()
        InitializeForm()
    End Sub

    ' The Click event is raised when the user clicks the Print button. 
    Private Sub printButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles printButton.Click
        Try
            streamToPrint = New StreamReader("D:\MyFile.txt")
            Try
                printFont = New Font("Arial", 10)
                Dim pd As New PrintDocument()
                AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
                pd.Print()
            Finally
                streamToPrint.Close()
            End Try
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    ' The PrintPage event is raised for each page to be printed. 
    Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
        Dim linesPerPage As Single = 0
        Dim yPos As Single = 0
        Dim count As Integer = 0
        Dim leftMargin As Single = ev.MarginBounds.Left
        Dim topMargin As Single = ev.MarginBounds.Top
        Dim line As String = Nothing

        ' Calculate the number of lines per page.
        linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)

        ' Print each line of the file. 
        While count < linesPerPage
            line = streamToPrint.ReadLine()
            If line Is Nothing Then
                Exit While
            End If
            yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
            ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
            count += 1
        End While

        ' If more lines exist, print another page. 
        If (line IsNot Nothing) Then
            ev.HasMorePages = True
        Else
            ev.HasMorePages = False
        End If
    End Sub

    Private Sub InitializeForm()
        Me.components = New System.ComponentModel.Container()
        Me.printButton = New System.Windows.Forms.Button()

        Me.ClientSize = New System.Drawing.Size(504, 381)
        Me.Text = "Print Example"

        printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft
        printButton.Location = New System.Drawing.Point(32, 110)
        printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        printButton.TabIndex = 0
        printButton.Text = "Print the file."
        printButton.Size = New System.Drawing.Size(136, 40)
        AddHandler printButton.Click, AddressOf printButton_Click

        Me.Controls.Add(printButton)
    End Sub


    ' This is the main entry point for the application.     
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

End Class

Rbie on Thu, 27 Mar 2014 07:13:55


The example from microsoft isn't complete (the event handler is missing

this line

Private Sub printDocument1_PrintPage(ByVal sender As Object, _
        ByVal e As PrintPageEventArgs)

should be

 Private Sub printDocument1_PrintPage(ByVal sender As Object, _
       ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage

Konstantina M on Thu, 27 Mar 2014 07:49:51


Sorry this did not correct the problem but thanks.

Rbie on Thu, 27 Mar 2014 09:19:31


could you show the code you use now, since the MS example works when I do it (with the handles added)

Franklin Chen on Fri, 28 Mar 2014 01:18:52


Sorry this did not correct the problem but thanks.

Please provide more details and what the issues you have faced

KonstantinaM on Tue, 01 Apr 2014 18:45:15


Hi,

I use the software Notepad and whenever it prints, it prints just white pages.


Code:

-Above of the "Public Class Form1":
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms

-Into the Form1:
Private Sub PrintFile()

        ReadFile()
        PrintDocument.Print()
    End Sub
    Private Sub ReadFile()
        OutputFile = DirPath + "\temp.txt"
        PrintDocument.DocumentName = OutputFile
        Dim stream As New FileStream(OutputFile, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                stringToPrint = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
    End Sub

What's wrong?

Konstantina.

KonstantinaM on Tue, 01 Apr 2014 18:45:41


Hi,

I use the software Notepad and whenever it prints, it prints just white pages.


Code:

-Above of the "Public Class Form1":
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms

-Into the Form1:
Private Sub PrintFile()

        ReadFile()
        PrintDocument.Print()
    End Sub
    Private Sub ReadFile()
        OutputFile = DirPath + "\temp.txt"
        PrintDocument.DocumentName = OutputFile
        Dim stream As New FileStream(OutputFile, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                stringToPrint = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
    End Sub

What's wrong?

Konstantina.

Franklin Chen on Wed, 02 Apr 2014 08:00:30


Hi,

I use the software Notepad and whenever it prints, it prints just white pages.


Code:

-Above of the "Public Class Form1":
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms

-Into the Form1:
Private Sub PrintFile()

        ReadFile()
        PrintDocument.Print()
    End Sub
    Private Sub ReadFile()
        OutputFile = DirPath + "\temp.txt"
        PrintDocument.DocumentName = OutputFile
        Dim stream As New FileStream(OutputFile, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                stringToPrint = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
    End Sub

What's wrong?

Konstantina.


Hi,

As Rbie suggested, you've missed the handler for PrintDocument.PrintPage event, here is the fixed code:

Imports System.Drawing.Printing
Imports System.IO

Public Class Form1
    WithEvents PrintDocument As New PrintDocument()
    Dim stringToPrint As String

    Private Sub PrintFile()

        ReadFile()
        PrintDocument.Print()
    End Sub
    Dim OutputFile As String
    Private Sub ReadFile()
        OutputFile = "E:\temp.txt"
        PrintDocument.DocumentName = OutputFile
        Dim stream As New FileStream(OutputFile, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                stringToPrint = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
    End Sub

    Private Sub printDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles PrintDocument.PrintPage

        Dim charactersOnPage As Integer = 0
        Dim linesPerPage As Integer = 0

        ' Sets the value of charactersOnPage to the number of characters  
        ' of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
            StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

        ' Draws the string within the bounds of the page
        e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
            e.MarginBounds, StringFormat.GenericTypographic)

        ' Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage)

        ' Check to see if more pages are to be printed.
        e.HasMorePages = stringToPrint.Length > 0

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PrintFile()
    End Sub
End Class

Mr. Monkeyboy on Wed, 02 Apr 2014 13:38:19


I used your code Franklin and as soon as I clicked Button1 I received a save file as .XPS document so I entered a filename and it brought the file up in XPS viewer. Because I have Microsoft XPS Document Writer as my default printer. Code worked awesome!

Franklin Chen on Thu, 03 Apr 2014 09:35:11


I used your code Franklin and as soon as I clicked Button1 I received a save file as .XPS document so I entered a filename and it brought the file up in XPS viewer. Because I have Microsoft XPS Document Writer as my default printer. Code worked awesome!


Hello. I'm old and retired. I like to program if you could call what I do programming. However I'd like to code for you! If you've got the dime then I've got the time. Call me, landline, @ BR-549.


Thank you, Monkeyboy;)

KonstantinaM on Fri, 04 Apr 2014 20:00:11


THANK YOU!!! Very happy, I finally print!