Print a pdf to a selected printer using iText7 - vb.net

I Need to print a pdf file to a selected printer.
I have tried using the code below, but it opens adobe and prints to the default printer. Does itext 7 have the ability to print directly to a selected printer using the print dialog box.
I am using visual basic.net
Dim proc As Process = New Process
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo.Verb = "print"
'Define location of adobe reader/command line
'switches to launch adobe in "print" mode
proc.StartInfo.FileName = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
proc.StartInfo.Arguments = "/p /h "" " & item & ""
proc.StartInfo.UseShellExecute = False
proc.StartInfo.CreateNoWindow = False
proc.Start()
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal
If (proc.HasExited = False) Then
proc.WaitForExit(10000)
End If
proc.EnableRaisingEvents = True
proc.Close()
killProcess("AcroRd32")

Related

Print PDF file with printdialog vb.net

I'm trying to print a external pdf file with printdialog options but the file is printed with predeterminated printer config
Dim result As DialogResult = PrintDialog1.ShowDialog()
If (result = DialogResult.OK) Then
Dim psi As New ProcessStartInfo
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = "file.pdf"
Process.Start(psi)
End If
You would need to use the "PrintTo" verb rather than the "Print" verb. You would also need to wrap the printer name in quotes if it might have spaces in it. I would suggest making your code a bit more succinct:
Process.Start(New ProcessStartInfo("file.pdf",
$"""{PrintDialog1.PrinterSettings.PrinterName}""") With {.Verb = "printto",
.UseShellExecute = True,
.WindowStyle = ProcessWindowStyle.Hidden})

Need to prompt user for UAC when attempting to open a share using Process.Start

This works, if the current user has rights to the UNC path. Opens it right up.
Process.Start("\\USERSHARE\VALUE\EMPLOYEES\")
However, I have to run the entire program as a user that doesn't have access to the UNC path due to SQL permissions in the code.
I made a button in the app that will open the UNC path in an explorer window, but I cannot figure out how to force a runas for the operation.
I have tried the following as well:
Dim procStartInfo As New ProcessStartInfo
Dim procExecuting As New Process
With procStartInfo
.UseShellExecute = True
.FileName = "Notepad.exe"
.WindowStyle = ProcessWindowStyle.Normal
.Verb = "runas" 'add this to prompt for elevation
End With
procExecuting = Process.Start(procStartInfo)
This works and prompts with UAC to open "notepad".
This doesn't work to open the UNC path:
Dim procStartInfo As New ProcessStartInfo
With procStartInfo
.UseShellExecute = True
.FileName = "\\USERSHARE\VALUE\EMPLOYEES\"
.WindowStyle = ProcessWindowStyle.Normal
.Verb = "runas" 'add this to prompt for elevation
End With
Process.Start(procStartInfo)
I understand opening the fileshare isn't the same as pointing the .FileName at an executable.
I'm having problems trying to have the app prompt for UAC before attempting to open the remote folder.
You don't want to execute the folder itself, but rather explorer.exe with the folder as an argument:
Dim procStartInfo As New ProcessStartInfo
With procStartInfo
.UseShellExecute = True
.FileName = "explorer.exe"
.Arguments = "\\USERSHARE\VALUE\EMPLOYEES\"
.WindowStyle = ProcessWindowStyle.Normal
.Verb = "runas" 'add this to prompt for elevation
End With
Process.Start(procStartInfo)

Change .SaveFile to save as keeping the file format

How can I turn this statement into a "save as" dialog box?
Me.TextBox4.SaveFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) + "\MyDocs\Test.xml", RichTextBoxStreamType.UnicodePlainText)
I need to preserve this format since it is the only one that worked properly when file is saved.
Thanks.
You can try something like this. Create a SaveFileDialog and pass it all the parameters for the default locations and file names. Create a new file stream based on your file (creating or overwriting) and passing that stream to the SaveFile method of the RichTextBox
Using sfd As New SaveFileDialog()
sfd.AddExtension = True
sfd.Filter = "*.xml|*.xml"
sfd.OverwritePrompt = True
sfd.DefaultExt = ".xml"
sfd.CreatePrompt = False
sfd.InitialDirectory = Path.Combine(Environment.SpecialFolder.MyComputer, "\MyDocs\")
sfd.FileName = "Test.xml"
If sfd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso sfd.FileName <> String.Empty Then
Using sf As New FileStream(sfd.FileName, FileMode.Create)
TextBox4.SaveFile(sf, RichTextBoxStreamType.UnicodePlainText)
End Using
End If
End Using

How to include the message box within the Open file dialog in VB.net

In my previous question: How to know if the file I'm opening is a .txt file or not in VB.net
I ask here how to know if I'm opening .txt file or not.
The code below is my code for opening a .txt file and prompt the user if the file is .txt of not.
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Dim ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
ofd1.FilterIndex = 2
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
'if the file is not .txt file
If (Path.GetExtension(filename).ToLower() <> ".txt") Then
MessageBox.Show("Please select text Files only", _
"RMI", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
'show the open file dialog
ofd1.ShowDialog()
'if the file is .txt file
Else
filename = ofd1.FileName
End If
'if the filename is existing
If System.IO.File.Exists(filename) = True Then
Dim objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End If
If the file that I selected is not .txt file, here is the output:
If I open a file that is not existing, here is the output:
In the 1st image, it only show the error message box, but in the 2nd image, the error message box is within the open file dialog.
My question is how can I show the error message box of the 1st image with the open file dialog?
Thank you.
Notes:
No need to check the extension after you show the form, but you should instead set the appropriate filter in order to limit the selection of .txt files only "txt files (*.txt)|*.txt"
You can use the OpenFileDialiog.CheckFileExists and OpenFileDialiog.CheckPathExists properties to prevent user to enter an invalid file name/path (display an error message)
Not sure you need to check a second time if the file exists if you use CheckFileExists / CheckPathExists
You should always dispose a form that you show using ShowDialog() method.
You should dispose the StreamReader
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Using ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt"
ofd1.FilterIndex = 2
ofd1.CheckPathExists = True
ofd1.CheckPathExists = True
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
Using objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End Using
End If
End Using
Here i add the label which is hidden. (name: pathlabel)
button (open file)
add openfiledialog from toolbox
this is so simple.
Open File button:
openfiledialog.showdialog()
OpenFileDialog_FileOk :
PathLabel.Text = System.IO.Path.GetExtension(OpenFileDialog.FileName)
If PathLabel.Text = ".txt" Then
Dim Objectreader As New System.IO.StreamReader(OpenFileDialog.FileName)
TextBox1.Text = Objectreader.ReadToEnd
Objectreader.Close()
Else
MsgBox("please select only Text Document (.txt)", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
End If
Thank you...
Instead of this you must set the filter to openfiledialog
button code (open file)
Openfiledialog.showdialog()
openfiledialog.filter = "Text Document|*.txt"

Wait for batch file to close before continuing - VB.net

I'm trying to run a batch file via VB and I need to wait for it to complete/exit before progressing. The issue I believe I am having is that when a batch file is executed, it opens cmd.exe and not the batch file.
This is what I am executing with VB
My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt")
FileCopy(My.Application.Info.DirectoryPath & "\machines.txt", My.Application.Info.DirectoryPath & "\PingCheck\machines.txt")
Dim psi As New ProcessStartInfo(My.Application.Info.DirectoryPath & "\PingCheck\go.bat")
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = False
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = process.Start(psi)
process.WaitForExit()
ProgressBar1.Value = ProgressBar1.Value + 2
FileCopy(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt", My.Application.Info.DirectoryPath & "\machines.txt")
'My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\ping.bat")
MsgBox("Ping Check Complete")
The problem im having is that it will just delete ping.bat before it completes.
How do I go about monitoring the process from the batch file I call. Then once it exits, continue with the script?
RHicke shows a nice example of how to run a batch process in VB.NET here, Run batch file in vb.net?.
To expand, you should use the function WaitForExit() to wait for the process to complete.
Dim psi As New ProcessStartInfo("Path TO Batch File")
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = False
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = Process.Start(psi)
process.WaitForExit()
You could use the System.Diagnostics.Process class to start the batch file. The process reference will give you access to the property HasExited (and more interesting information). The HasExited property indicates whether a process has completed.
var process = System.Diagnostics.Process.Start(new ProcessStartInfo
{
FileName = "batch file path",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
Arguments = "parameters if applicable",
CreateNoWindow = true
});
while(!process.HasExited)
{
// obviously do some clever here to wait
}
Code is in C# but the principle should work in VB.NET
I've done something similar before. This code invokes RoboCopy from within VB.Net, using the System.Diagnostics.Process (mentioned by rivethead_).
Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process()
proc.EnableRaisingEvents = False
proc.StartInfo.FileName = "d:\robocopy\robocopy"
proc.StartInfo.Arguments = strSrcDir & " " & strDestDir & " " & strFile & " " & My.Settings.robocopyFlags
proc.Start()
proc.WaitForExit()
Otherwise, what is the ping.bat doing? Is it just doing a "ping" command? If so, maybe you could invoke that with a System.Diagnostics.Process (instead of invoking a .bat file to do it). That might give you some more control over your process.