Print Preview not displaying file - vb.net

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

Related

Find REGEX in every file in a folder

I need to evaluate each file in a folder for the ICN string. Then add each ICN to an output file. I found the code below and have made changes to it to meet my needs but it only adds one found file in the ICN.log instead of looping through all files.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
End Sub
After I removed the for exit for the code works.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
'MsgBox(tFile)
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
'Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
MsgBox("Function Complete")
End Sub

Download a selected file from my GridView using DoubleClick

I am trying to download a file that I uploaded into my GridView. Each time I double click on the second document in the GridView, it opens the first uploaded document and saves it
Here is my code:
Private Sub dgDocuments_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Handles dgDocuments.DoubleClick
LoadUploadedDocuments()
Try
Dim objTransactionDocument As Objects.TransactionsDocuments
If dgDocuments.CurrentRowIndex.Equals(-1) Then
Dim obj As Object = dgDocuments.Item(dgDocuments.CurrentRowIndex, 1)
objTransactionDocument = Managers.TransactionsDocuments.SelectTransactionsDocuments(Convert.ToInt32(obj))
End If
If Not objTransactionDocument Is Nothing Then
If objTransactionDocument.TransactionsDocumentsID = 1 Then
Dim saveFile As New SaveFileDialog
saveFile.FileName = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
saveFile.Title = "Download supporting document to transaction " + m_objTransaction.TransactionID.ToString()
If saveFile.ShowDialog() = DialogResult.OK Then
Dim saveDir As String = Path.GetDirectoryName(saveFile.FileName)
Dim name As String = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
Dim saveLocation As String = saveDir + name
System.IO.File.Copy(objTransactionDocument.FileLocation, saveLocation)
MessageBox.Show("Document saved successfully")
End If
End If
End If
Catch ex As Exception
MessageBox.Show("Document saved unsuccessfully " + ex.ToString())
End Try
End Sub
What am I doing wrong?
add / to saveDir as
saveDir+='/'

All text in listbox to a specific location in MS Word Document

I am trying to transfer all the text in listbox to a particular place in MS Word Document, similar to bookmark. I've also tried doing a style in bookmarked but only the first line is showing.
The problem that I have is that I need to transfer the contents of a ListBox to the Word doc and have not got a clue how to do it.
Please kindly help if you can.
Here's my code.
Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
#Region "dim"
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim WPath = IO.Path.Combine(exeDir.DirectoryName, "SampleReceipt.doc")
Dim Word As Word.Application
Dim Doc As Word.Document
#End Region
Private Sub NAR(ByVal o As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
Catch ex As Exception
o = Nothing
Finally
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Word = New Word.Application
Word.Visible = True
Doc = Word.Documents.Open(WPath)
Word.ActiveDocument.Bookmarks("txtDate").Select()
Word.Selection.Text = (TextBox1.Text)
Word.ActiveDocument.Bookmarks("txtSchoolYear").Select()
Word.Selection.Text = (TextBox2.Text)
Word.ActiveDocument.Bookmarks("txtr1").Select()
Word.Selection.Text = List1.Text
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
List1.Items.Add("string1")
List1.Items.Add("string2")
List1.Items.Add("string3")
End Sub
End Class
To create a string from the items in a ListBox, just use the following function
Private Function GetListBoxStrings() As String
Dim tempString As String = ""
For Each line As String In List1.Items
tempString = tempString & line
Next
Return tempString
End Function
and use it liike so
Word.ActiveDocument.Bookmarks("txtr1").Select()
Word.Selection.Text = GetListBoxStrings()

Search through text file and return a line of text

I am trying to create a program that will search a text file for a line of text and then return the full line of information.
Example line: Joe Blogs JBL 1234
Search: Joe Blogs
Search returns: Joe Blogs JBL 1234
To make it as simple as possible, I have 2 text boxes & 1 button.
Textbox1 = search
Textbox2 = Search results
Button = Search button
Can anyone tell me how to do this because I'm finding it really difficult. I'm new to VB coding so the simplest of code would be helpful!
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Input Text Error
If TextBox1.TextLength = 0 Then
MsgBox("Please enter a Staff Name or Staff Code", MsgBoxStyle.Information, "Error")
End If
'Perform Search
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", TextBox1.Text)
If strText <> String.Empty Then
TextBox2.Text = strText
End If
End Sub
'Search Function
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
'Clear Button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = ""
TextBox1.Text = ""
End Sub
' Open The text file
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Process.Start("C:\Users\kylesnelling\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt")
End Sub
End Class
Whenever I perform a search, all I get back is the last line of the text file... does anyone know why?
As Alex B has stated in comments, line If strLine.Contains("textbox1.text") should be If strLine.Contains(strSearchTerm)
Also you are not passing in the search item to the function. The below line you have passed in the string textbox1.text as a string rather than the text inside the textbox. Hence why you never find the line you are searching for and always returns the last record of your file.
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", "textbox1,text")
This line should be:
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", textbox1.text)
Also with this line Dim sr As StreamReader = New StreamReader("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt") why have you used the same path destination when you have already passed in this file location in the variable strFilePath.
line should be Dim sr As StreamReader = New StreamReader(strFilePath)
Its best to use the variables being passed into the function otherwise this function won't be very useful to other parts of code that may be referencing it or if search terms or filepaths change.
Updated from comments:
strLine.ToUpper.Contains(strSearchTerm.ToUpper) this line will make both text uppercase and the word you are searching for to uppercase, which will allow them to ignore case sensitivity, so for example, "text" can match with "Text" by both being converted to "TEXT" when used to compare.
Give this a try friend.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchResult As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", _
"text to search for")
Me.TextBox2.Text = searchResult
End Sub
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim fs As New System.IO.StreamReader(strFilePath)
Dim currentLine As String = String.Empty
Try
Dim searchResult As String = String.Empty
Do While fs.EndOfStream = False
currentLine = fs.ReadLine
If currentLine.IndexOf(strSearchTerm) > -1 Then
searchResult = currentLine
Exit Do
End If
Loop
Return searchResult
Catch ex As Exception
Return String.Empty
End Try
End Function

How to print text files?

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 ...