How to print text files? - vb.net

I've created and saved a .txt file and now I'm truing to print it. The file could be big enough where multiple pages would be needed. Here is my code:
'Print file
Dim docName As String = name1 & " " & name2 & ".txt"
Dim docPath As String = "Z:\\Completed\"
printDocument1.DocumentName = docName
Dim stream As New FileStream(docPath & docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
stringToPrint = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
printDocument1.Print()
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As PrintPageEventArgs)
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
My issue is that it prints a blank page every time. Stepping through the code I can see that "docName" and "docPath" are set correctly.
Example:
docName = Test 1.txt
docPath = Z:\Completed\

The MSDN example is very unclear (the example code doesn't even show it), but you have to manually add the PrintPage event handler. Add this line after you declare printDocument1, but before you call printDocument1.Print():
AddHandler printDocument1.PrintPage, AddressOf printDocument1_PrintPage
Alternately, you could change your Sub declaration to:
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage
Edit: To use this method, you have to declare printDocument1 using the WithEvents keyword, something like this:
Dim WithEvents printDocument1 As ...

Related

VB NET problems with background worker

While my background worker is doing his job, I want to change a label in main form telling what process is taking in that time.
The app works with some files, so I need to pass the information of the file the app is working on.
My Background Worker
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If (Not System.IO.Directory.Exists(caminho & "\results")) Then
System.IO.Directory.CreateDirectory(caminho & "\results")
End If
For Each folder As String In System.IO.Directory.GetDirectories(caminho)
Dim split As String() = folder.Split("\")
Dim parentFolder As String = split(split.Length - 1)
If (Not System.IO.Directory.Exists(caminho & "\results" & "\" & parentFolder)) Then
System.IO.Directory.CreateDirectory(caminho & "\results" & "\" & parentFolder)
End If
For Each file As String In System.IO.Directory.GetFiles(folder)
output = file
'Dim imgFile As System.Drawing.Image = System.Drawing.Image.FromFile(file)
Dim thumbimage As Bitmap
Dim originalimage As Bitmap
Dim width As Integer = TextBox2.Text '# this is the max width of the new image
Dim height As Integer = TextBox3.Text '# this is the max height of the new image
originalimage = System.Drawing.Image.FromFile(file)
thumbimage = New Bitmap(width, height)
Dim novonome As String = Path.GetFileNameWithoutExtension(file)
Dim gr As Graphics = Graphics.FromImage(thumbimage)
gr.DrawImage(originalimage, 0, 0, width, height)
thumbimage.Save(caminho & "\results" & "\" & parentFolder & "\" & novonome & ".png", Imaging.ImageFormat.Png)
thumbimage.Dispose()
originalimage.Dispose()
Next
Next
End Sub
My On Progress Change:
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Label3.Text = "Working file " & output
End Sub
Isn't supposed to change the label3.text in form1 with the file it's working? Basically nothing happens to label3.
My output var is declared under Public Class Form1.
Thanks in advance.
Make sure your BackgroundWorker object has WorkerReportsProgress = True
You have to call the progress from within your loop:
For Each file As String In System.IO.Directory.GetFiles(folder)
BackgroundWorker1.ReportProgress(0, file)
...
Then in your Progress event, read the status:
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If e.UserState IsNot Nothing Then
Label3.Text = "Working file " & e.UserState.ToString
End If
End Sub

How to get line number from a text file in vb.net

I am making a program where i have 2 text files and i want 2 get one line from each text file like this
Dim pathlocal as string= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Test\"
Dim reader As New System.IO.StreamReader(pathlocal & "to.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
For Each file In allLines
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(file).Name) Then
'Get line number of from.txt where you found file.name
End If
End If
Next
I appreciate the help(and pls try 2 make it simple sorry but i am not that good THANX)
This might help you:
Imports System.IO
Imports System
Imports System.Collections.Generic
Public Class Form1
Dim path As String = "Your Path"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim indxto As Integer = 0
Dim indxfrom As Integer = 0
Dim allLinesto As List(Of String) = File.ReadAllLines(path & "\" & "to.txt").ToList
Dim allLinesfrom As List(Of String) = File.ReadAllLines(path & "\" & "from.txt").ToList
For Each line As String In allLinesto
indxto = allLinesto.IndexOf(line)
'Debug.Print(line & " " & indxto.ToString)
For Each item As String In allLinesfrom
indxfrom = allLinesto.IndexOf(item)
If line = item Then
Debug.Print(item & " " & indxfrom.ToString)
End If
Next
Next
End Sub
End Class
You can instantiate a couple of Integer typed variables to help with this. One stores the line number as you iterate through the list and the other stores the line number you are seeking. Plus, by changing your For Each approach to a Do Until or Do While approach you could potentially speed things up if the target is found prior to the last line of the file.
Dim intLineNumber As Integer = -1
Dim intLineCursor As Integer
Do Until (intLineCursor = allLines.Count OrElse intLineNumber <> -1)
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(allLines(intLineCursor)).Name) Then
intLineNumber = intLineCursor '+ 1 if you are displaying to a user since the lower bound is 0 based.
End If
'Increment the cursor variable.
intLineCursor += 1
Loop

vb.net 2010 PrintDocument Margins not working even if I set the margins

I am reading from a text file and then printing the string using printdocument via vb.net 2010.
Here is my code :
Public Class myPrinter
Friend TextToBePrinted As String
Public Sub prt(ByVal text As String)
Dim psize As New System.Drawing.Printing.PaperSize("Custom Paper Size", 850, 550)
Dim newMargins As New System.Drawing.Printing.Margins(0, 0, 0, 0)
TextToBePrinted = text
Dim prn As New Printing.PrintDocument
Using (prn)
prn.PrinterSettings.PrinterName = frmStockOut.printer
prn.PrinterSettings.Copies = frmStockOut.copies
prn.PrinterSettings.DefaultPageSettings.PaperSize = psize
prn.PrinterSettings.DefaultPageSettings.Margins = newMargins
prn.DefaultPageSettings.PaperSize = psize
prn.DefaultPageSettings.Margins = newMargins
AddHandler prn.PrintPage, _
AddressOf Me.PrintPageHandler
prn.Print()
RemoveHandler prn.PrintPage, _
AddressOf Me.PrintPageHandler
End Using
End Sub
Private Sub PrintPageHandler(ByVal sender As Object, _
ByVal args As Printing.PrintPageEventArgs)
Dim myFont As New Font("Courier New", 11)
args.Graphics.DrawString(TextToBePrinted, _
New Font(myFont, FontStyle.Regular), _
Brushes.Black, 50, 50)
End Sub
End Class
Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.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 Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ReadFile() ' will read text file and store in a string
Dim Print As New myPrinter
Dim myprintdialog As New PrintDialog
With myprintdialog
If .ShowDialog = Windows.Forms.DialogResult.OK Then
printer = .PrinterSettings.PrinterName
copies = .PrinterSettings.Copies
Print.prt(stringToPrint)
End If
End With
End Sub
The problem is even after I set the left margin and top margin to 0, it seems nothing has changed, it is still printing almost 3/4 inch for top margins and 1 inch for the left margin. This is also the output when I didn't set the margins. However, when I prn.OriginAtMargins = True , the output becomes a little different, left margin is now almost 1/2 inch but top margin remains the same. Something wrong with my code?
What I want to accomplish is the top margin can be set at approximately 20 pixels (assuming 100 pixels is equal to 1 inch) and left margin be set at 20 pixels too. Hope somebody can help me.

Print Preview not displaying file

I am working on a menu strip Print Preview event. i worked out the following procedure to view a pdf file located in the same path as my workbook.
Private WithEvents docPrint As New PrintDocument()
' Declare a string to hold the entire document contents.
Private documentContents As String
' Declare a variable to hold the portion of the document that
' is not printed.
Private stringToPrint As String
Private Sub ReadDocument()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
Dim stream As New FileStream(docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
documentContents = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
stringToPrint = documentContents
End Sub
Private Sub prnPrvStripCustomRange_Click(sender As Object, e As EventArgs) Handles prnPrvStripCustomRanges.Click
ReadDocument()
prnPrvCustomRanges.Document = docPrint
prnPrvCustomRanges.ShowDialog()
End Sub
The dialog pops up on click, but my document page is blank. I have another event for printing and that one prints the same document. So I don't understand what I am doing wrong on my preview.
Here is my print procedure:
Private Sub prnCustonPages_Click(sender As Object, e As EventArgs) Handles prnCustonPages.Click
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
prnPrtCustomRanges.Document = docPrint
prnPrtCustomRanges.PrinterSettings = docPrint.PrinterSettings
prnPrtCustomRanges.AllowSomePages = True
If prnPrtCustomRanges.ShowDialog = DialogResult.OK Then
docPrint.PrinterSettings = prnPrtCustomRanges.PrinterSettings
docPrint.Print()
End If
End Sub

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub