Display list of printers and select the default one using VB.Net - vb.net

I have this code that will display all the installed printers on my computer. What I wanted to do next is that display by default as soon as the form loads the default printer on my computer. Any help is greatly appreciated.
Dim objSettings As New Printing.PrinterSettings
Dim strPrinter As String
Try
For Each strPrinter In Printing.PrinterSettings.InstalledPrinters
cmbPrinters.Items.Add(strPrinter)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try

cmbPrinters.SelectedText = objSettings.PrinterName.ToString
If you put this on your form load, it will give you the default printer. Printer settings is initialised with the default values so will display the default printer.

Related

How to print HTML without WebBrowser control and Acrobat window?

I know my question is not focused on a precise problem but Google ran out of results. I'm trying to make a little app in Visual Basic .Net and have a HTML string which needs to be printed to a specific printer, and the problem is that i've tried to:
write out to a HTML file then print it with a WebBrowser: the problem is that i can't print to a specific printer, only to the default one.
convert it to a PDF with htmlToPdf package but: (1) it needs Acrobat Reader AND file association in Windows, (2) it opens the Acrobat Reader which is not quite professional.
EDIT
Thanks to a solution provided by the first commenter, i've made it partially. The problem is that the first document is printed perfectly, but the next ones are printed to the first specified printer (in Devices and Printers the default printer changes but the target printer remains the first one) Here is the code:
Public Sub PrintHTML(ByVal text As String, ByVal printer As String)
Try
LogData("Changing default printer to " & printer)
Dim wtype = Type.GetTypeFromProgID("WScript.Network")
Dim instance = Activator.CreateInstance(wtype)
wtype.InvokeMember("SetDefaultPrinter", System.Reflection.BindingFlags.InvokeMethod, Nothing, instance, New Object() {printer})
Catch ex As Exception
LogData("Changing failed...")
LogData(ex.ToString)
Finally
LogData("PrintHTML Init with " & printer)
Me.wbForPrint.Navigate("about:blank")
If Not WebBrowserReadyState.Interactive = WebBrowserReadyState.Complete Then
Me.wbForPrint.Stop()
End If
Me.wbForPrint.DocumentText = text
AddHandler (Me.wbForPrint.DocumentCompleted), AddressOf HTMLDocumentCompleted
End Try
End Sub
If the printing needs to be automatic with any user input then you could use this code to change the default printer, and then restore the default printer back to what it was once you have done the printing (source: http://codesnippets.fesslersoft.de/how-to-set-the-default-printer-in-c-and-vb-net/)
Public Shared Sub SetDefaultPrinter(ByVal printername As String)
Dim type As var = Type.GetTypeFromProgID("WScript.Network")
Dim instance As var = Activator.CreateInstance(type)
type.InvokeMember("SetDefaultPrinter", System.Reflection.BindingFlags.InvokeMethod, Nothing, instance, New Object() {printername})
End Sub
Or if you want the user to choose which printer to send to, you could try:
WebBrowser1.ShowPrintPreviewDialog()
or
WebBrowser1.ShowPrintDialog()

Select Printer to Print PDF file in vb.net

I have to select a printer and print a PDF file.
here i used, this code prints ONLY in the default printer.. i tired for searching and didn't find a solution.
Dim PrintPDF As New ProcessStartInfo
PrintPDF.UseShellExecute = True
PrintPDF.Verb = "print"
PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
PrintPDF.FileName = "temp.pdf" 'fileName is a string parameter
Process.Start(PrintPDF)
i had done another part to find the printers in dropdown list
this code to find printer
Dim pkInstalledPrinters As String
For Each pkInstalledPrinters In PrinterSettings.InstalledPrinters
ComboBox1.Items.Add(pkInstalledPrinters)
Next pkInstalledPrinters
ComboBox1.SelectedIndex = ComboBox1.Items.Count - 1
Is there any Suggestions?
Thanks.
Try this,
I have added a web browser control in form.
add file file name of your pdf filename as follows:
WebBrowser1.naviagte(YourFileName)
Try
WebBrowser1.Print()
Catch ex As Exception
MsgBox(ex.Message)
End Try
While Doing this your app show print dialog with inbuilt option with which printer to you need to print.

How do I load the same Crystal Report twice?

For some reason I can't load this report twice in one program session. I can print it the first time without a problem. The second time I get the error:
CrystalDecisions.Shared.CrystalReportsException: Load report failed.
Here is my code for this segment.
Private Sub Print_Report()
Using CrystalReport As New ReportDocument
CrystalReport.Load("Reports\PrintMe.rpt")
CrystalReport.SetParameterValue("Code", txtCode.Text)
CrystalReport.SetParameterValue("Control", txtControl.Text)
CrystalReport.PrintOptions.PrinterName = DefaultPrinterName()
CrystalReport.PrintToPrinter(1, True, 0, 0)
End Using
End Sub
Private Function DefaultPrinterName() As String
Dim psDefault As New System.Drawing.Printing.PrinterSettings
Try
DefaultPrinterName = psDefault.PrinterName
Catch ex As System.Exception
DefaultPrinterName = ""
Finally
psDefault = Nothing
End Try
End Function
All I can think is that the file isn't being let go at the end of the first print. Am I over looking something simple?
The issues was caused by using Foxit Reader's PDF Printer. I switched to using Adobe Acrobat and the issue is now gone. I'm only using the PDF Printer for printer tests to save paper. I will be using the Export to Disk for anything PDF related.

Print rdlc report without viewing print dialogue box

I have am writing a POS application, which requires to print invoice very often.
I need to send it directly to printer instead of viewing the print dialogue. Using Reportviewer_renderingcomplete, I can avoid seeing the report but I do not know how to avoid seeing the print dialogue box and print report without user intervention?
Thanks a lot.
Here is how you can do it:
Dim m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Dim report As New LocalReport()
report.DataSources.Add(New ReportDataSource("testData", reportData.Tables(0)))
report.ReportEmbeddedResource = "ReportsLibrary.rptTestData.rdlc"
Dim deviceInfo As String = "<DeviceInfo><OutputFormat>EMF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight><MarginTop>0.25in</MarginTop><MarginLeft>0.25in</MarginLeft><MarginRight>0.25in</MarginRight><MarginBottom>0.25in</MarginBottom></DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
Dim printDoc As New PrintDocument()
printDoc.PrinterSettings.PrinterName = "<your default printer name>"
Dim ps As New PrinterSettings()
ps.PrinterName = printDoc.PrinterSettings.PrinterName
printDoc.PrinterSettings = ps
printDoc.PrintPage += New PrintPageEventHandler(PrintPage)
m_currentPageIndex = 0
printDoc.Print()
Where PrintPage defined as follows:
' Handler for PrintPageEvents
Private Sub PrintPage(sender As Object, ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), ev.PageBounds.Width, ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
This is an interesting walkthrough by Microsoft: Printing a Local Report without Preview.
It's a different approach from yours because it prints directly a report without using ReportViewer and RenderingComplete event.
In order to not display PrintDialog box you must set printDoc.PrinterSettings.PrinterName with your default printer name.
Maybe you can store this value in a user configuration file.
It is actually far more simple than you would have imagined.
Within your form, include a "PrintDocument" component from the Toolbox.
Within your code behind, you will want to call the following method on your newly added component.
PrintDoc.Print()
The documentations state that the Print() "Starts the document's printing process". It will automatically begin printing the default set printer.
As tezzo mentioned, to set the Printer manually you can use the following snippet:
PrintDoc.PrinterSettings.PrinterName = "YourPrinterNameHere"
PrintDoc.PrinterSettings.PrinterName "gets or sets the name of the printer to use" as according to documentation. And if you need any further help, check out this video.
Please note however that video does not mention how to print "silently". It is just a good reference for beginners to see how the Print Components work together.

Try catch if selected excel file is blank

Hello I have a program that imports an excel file using the oledb in vb.net. This program imports the excel spreadsheet into a datagridview. On opening the program will ask the user to choose an excel file to open, however if the user inputs nothing or presses the cancel button the program will crash. I'm trying to find a way to prevent a user from canceling or leaving the excel filename blank. I'm hoping this will be done using a try catch block but I'm not exactly familiar with try catch in vb.net. If anyone has any suggestions or solutions for this I would greatly appreciate it. This is what I found on MSDN.
If System.IO.File.Exists(filePath) = False Then
Console.Write("File Not Found: " & filePath)
Else
' Open the text file and display its contents.
Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)
Console.Write(sr.ReadToEnd)
sr.Close()
End If
You could try a Try....Catch loop. Check this site out, should give you what you are looking for.
You could possibly use the Try....Catch loop and on the catch have an error message saying they must fill in the blank textbox.
I would suggest to take care of this at the source, when opening the file, and catching errors after the fact should be a last resort.
If filePath <> String.Empty And System.IO.File.Exists(filePath) Then
Try
'handle the opening of the file
Catch ex As Exception
Console.Write(ex.Message)
End Try
ElseIf filePath = String.Empty Then
Console.Write("Nothing Entered")
Else
Console.Write("File Not Found: " & filePath)
End If