Changing driver settings for printing a PDF - vb.net

How can I change settings in my printer (driver), before printing out a PDF?
To be more specific - I want to force my printer driver to use a printer settings instead of driver defaults - basically an equivalent of clicking Properties in a Print window (which opens printer-specific settings), then Advanced Setup and ticking "Use printer settings" checkbox which is by default unticked.
But it could be anything, for example changing dithering mode in a printer.
Here is the functioning code I'm using right now for printing a PDF using my network printer:
Dim PrinterName As String = "\\MyNetwork\ZDesigner ZM400 200 dpi (ZPL)"
Dim WshNetwork = CreateObject("WScript.Network")
WshNetwork.SetDefaultPrinter(PrinterName)
Dim PrintingPageSettings As New Printing.PageSettings()
Me.Text = PrintingPageSettings.PrinterSettings.PrinterName()
Dim isInstalled As Boolean = False
For Each InstalledPrinter As String In Printing.PrinterSettings.InstalledPrinters()
If (PrintingPageSettings.PrinterSettings.PrinterName() = InstalledPrinter.ToString) Then
isInstalled = True
End If
Next
If (isInstalled) Then
AdobeAcrobatCOM.src = Path
AdobeAcrobatCOM.printAll()
Else
Me.Text = PrinterName & " not found"
End If
AdobeAcrobatCOM is AxAcroPDFLib.AxAcroPDF (Adobe PDF Reader from Toolbox, COM components)

Eventually I used TCP connection to the printer and printed it out this way. Here is a code sample:
Dim PrintString As String
Dim ipAddress As String
Dim port As Integer
'123123 is sample integer, "TESTstring" is sample string, Space(2) is sample of adding (two) spaces
PrintString = String.Concat("^XA", "^FO060,080", "^BXN,5,200", "^FD", "TESTstring", 123123, "%^FS", "^FO160,100", "^ACourier,14,14", "^FD", Space(2), "^FS", "^XZ")
ipAddress = "ZDesigner ZM400 200 dpi (ZPL)" 'yes, this works too
port = 9100
'Open Connection
Dim client As New System.Net.Sockets.TcpClient
client.Connect(ipAddress, port)
'Write ZPL String to Connection
Dim writer As New System.IO.StreamWriter(client.GetStream())
writer.Write(PrintString)
writer.Flush()
'Close Connection
writer.Close()
client.Close()
You might want to look for your printer documentation. Here is a C# example for Zebra.

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()

Printing a .ZPL file to a zebra printer in vb.net. Visual Studio 2015 version

I already have the raw ZPL file ready to go, I just don't know how to set the printer I want to send it to and then send it. How would I do this?
Note: I have a batch script on my computer that I default all ZPL files to, which is a shell script that sends the file to the thermal printer on my computer. I want to get away from that and have all the commands within my application so I don't have to use an external script like that.
This is the code I have now that when ran it auto opens with my batch script:
Sub SaveLabel(ByRef labelFileName As String, ByRef labelBuffer() As Byte)
' Save label buffer to file
Dim myPrinter As New PrinterSettings
Dim LabelFile As FileStream = New FileStream(labelFileName, FileMode.Create)
LabelFile.Write(labelBuffer, 0, labelBuffer.Length)
LabelFile.Close()
' Display label
DisplayLabel(labelFileName)
End Sub
Sub DisplayLabel(ByRef labelFileName As String)
Dim info As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo(labelFileName)
info.UseShellExecute = True
info.Verb = "open"
info.WindowStyle = ProcessWindowStyle.Hidden
info.CreateNoWindow = True
System.Diagnostics.Process.Start(info)
End Sub
And this is my batch script:
copy %1 \\%ComputerName%\Zebra
To replicate the exact functionality of the batch file in VB.net:
Dim filename As String = System.IO.Path.GetFileName(labelFileName)
System.IO.File.Copy(
labelFileName,
Environment.ExpandEnvironmentVariables("\\%ComputerName%\Zebra\" & filename))
This copies the file using the method provided by the System.IO namespace. It also expands the %COMPUTERNAME% environment variable. This replaces all the code in the DisplayFile subroutine.

Printing an external PDF document in VB.net

I know this question has been asked before, but my situation is a bit wonky.
Basically, I'm trying to print a PDF file that I've generated using a previous Windows Form. I can find the file no problem, and I used the following code which I found off MSDN's help forums:
Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "C:\534679.pdf" 'This is the file name
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
So far so good, but everytime I press the button to run this code, it keeps asking me to save it as a PDF file instead, as shown below:
I've also tried adding a PrintDialog to the Windows Form, getting it to pop up, and I can select the printer I want to use from there, but even after selecting the printer it still asks me to print to PDF Document instead.
What am I doing wrong?
To print massive PDF documents with VB.Net you can use LVBPrint and run it via command line:
http://www.lvbprint.de/html/gsbatchprint1.html
For Example:
C:\temp\gsbatchprint64\gsbatchprintc.exe -P \\server\printer -N A3 -O Port -F C:\temp\gsbatchprint64\Test*.pdf -I Tray3
I use the following function in my application:
' print a pdf with lvbrint
Private Function UseLvbPrint(ByVal oPrinter As tb_Printer, fileName As String, portrait As Boolean, sTray As String) As String
Dim lvbArguments As String
Dim lvbProcessInfo As ProcessStartInfo
Dim lvbProcess As Process
Try
Dim sPrinterName As String
If portrait Then
lvbArguments = String.Format(" -P ""{0}"" -O Port -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
Else
lvbArguments = String.Format(" -P ""{0}"" -O Land -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
End If
lvbProcessInfo = New ProcessStartInfo()
lvbProcessInfo.WindowStyle = ProcessWindowStyle.Hidden
' location of gsbatchprintc.exe
lvbProcessInfo.FileName = LvbLocation
lvbProcessInfo.Arguments = lvbArguments
lvbProcessInfo.UseShellExecute = False
lvbProcessInfo.RedirectStandardOutput = True
lvbProcessInfo.RedirectStandardError = True
lvbProcessInfo.CreateNoWindow = False
lvbProcess = Process.Start(lvbProcessInfo)
'
' Read in all the text from the process with the StreamReader.
'
Using reader As StreamReader = lvbProcess.StandardOutput
Dim result As String = reader.ReadToEnd()
WriteLog(result)
End Using
Using readerErr As StreamReader = lvbProcess.StandardError
Dim resultErr As String = readerErr.ReadToEnd()
If resultErr.Trim() > "" Then
WriteLog(resultErr)
lvbProcess.Close()
Return resultErr
End If
End Using
If lvbProcess.HasExited = False Then
lvbProcess.WaitForExit(3000)
End If
lvbProcess.Close()
Return ""
Catch ex As Exception
Return ex.Message
End Try
End Function
I discourage on using AcrRd32.exe as it doesn't work with massive printings.
First, to be able to select a Printer, you'll have to use a PrintDialog and PrintDocument to send graphics to print to the selected printer.
Imports System.Drawing.Printing
Private WithEvents p_Document As PrintDocument = Nothing
Private Sub SelectPrinterThenPrint()
Dim PrintersDialog As New PrintDialog()
If PrintersDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
Try
p_Document = New PrintDocument()
PrintersDialog.Document = p_Document
AddHandler p_Document.PrintPage, AddressOf HandleOnPrintPage
Catch CurrentException As Exception
End Try
End If
End Sub
Private Sub HandleOnPrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles p_Document.PrintPage
Dim MorePagesPending As Boolean = False
'e.Graphics.Draw...(....)
'e.Graphics.DrawString(....)
' Draw everything...
If MorePagesPending Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
That's what I'm doing since I usually have custom objects to print.
But to print PDF Files, you must understand that PDF means absolutely nothing to dotNet. Unlike common images like Bitmaps (.bmp) or Ping images (.png) the dotNet doesn't seem to have any inbuilt parser/decoder for reading, displaying and printing PDF files.
So you must use a third party application, thrid party library or your own custom PDF parser/layout generator in order to be able to send pages to print to your printer.
That's why you can't launch a hidden (not visible) process of Acrobat Reader with the command "print". You won't be able to select a printer but will direct to the default one instead !
You can however launch the Acrobat Reader process just to open the file, and do the printing manipulations (select a printer) inside Acrobat Reader (you're outside dotNet coding now)
A workaround for your may aslo to select another default printer by opening Acrobat Reader, and print one blank page on an actual working printer. This should deselect your FoxIt thing in favour of an actual printer..
This code will help you to print in a specific printer.
The sample print a file using a ProcessStartInfo and a specific printer you can change the printer to use in the process.
If the print process is not finished after 10 seconds we kill the print process.
'Declare a printerSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click
Try
dim fileName As String = "C:\534679.pdf"
'Get de the default printer in the system
defaultPrinterSetting = DocumentPrinter.GetDefaultPrinterSetting
'uncomment if you want to change the default printer before print
'DocumentPrinter.ChangePrinterSettings(defaultPrinterSetting)
'print your file
If PrintFile(fileName, defaultPrinterSetting) then
msgbox ("your print file success message")
else
msgbox ("your print file failed message")
end if
Catch ex As Exception
mssbox(ex.Message.toString)
End Try
End Sub
Public NotInheritable Class DocumentPrinter
Shared Sub New()
End Sub
Public Shared Function PrintFile(ByVal fileName As String, printerSetting As System.Drawing.Printing.PrinterSettings) As Boolean
Dim printProcess As System.Diagnostics.Process = Nothing
Dim printed As Boolean = False
Try
If PrinterSetting IsNot Nothing Then
Dim startInfo As New ProcessStartInfo()
startInfo.Verb = "Print"
startInfo.Arguments = defaultPrinterSetting.PrinterName ' <----printer to use----
startInfo.FileName = fileName
startInfo.UseShellExecute = True
startInfo.CreateNoWindow = True
startInfo.WindowStyle = ProcessWindowStyle.Hidden
Using print As System.Diagnostics.Process = Process.Start(startInfo)
'Close the application after X milliseconds with WaitForExit(X)
print.WaitForExit(10000)
If print.HasExited = False Then
If print.CloseMainWindow() Then
printed = True
Else
printed = True
End If
Else
printed = True
End If
print.Close()
End Using
Else
Throw New Exception("Printers not found in the system...")
End If
Catch ex As Exception
Throw
End Try
Return printed
End Function
''' <summary>
''' Change the default printer using a print dialog Box
''' </summary>
''' <param name="defaultPrinterSetting"></param>
''' <remarks></remarks>
Public Shared Sub ChangePrinterSettings(ByRef defaultPrinterSetting As System.Drawing.Printing.PrinterSettings)
Dim printDialogBox As New PrintDialog
If printDialogBox.ShowDialog = Windows.Forms.DialogResult.OK Then
If printDialogBox.PrinterSettings.IsValid Then
defaultPrinterSetting = printDialogBox.PrinterSettings
End If
End If
End Sub
''' <summary>
''' Get the default printer settings in the system
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetDefaultPrinterSetting() As System.Drawing.Printing.PrinterSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
For Each printer As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
defaultPrinterSetting = New System.Drawing.Printing.PrinterSettings
defaultPrinterSetting.PrinterName = printer
If defaultPrinterSetting.IsDefaultPrinter Then
Return defaultPrinterSetting
End If
Next
Return defaultPrinterSetting
End Function
End Class
I used this code to print my PDF files on VB NET:
Dim PrintPDF As New ProcessStartInfo
PrintPDF.UseShellExecute = True
PrintPDF.Verb = "print"
PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
PrintPDF.FileName = dirName & fileName 'fileName is a string parameter
Process.Start(PrintPDF)
When you do this, process remains open with a adobe reader window that users have to close manually. I wanted to avoid user's interaction, just want them to get their documents. So, I added a few code lines to kill process:
Private Sub killProcess(ByVal processName As String)
Dim procesos As Process()
procesos = Process.GetProcessesByName(processName) 'I used "AcroRd32" as parameter
If procesos.Length > 0 Then
For i = procesos.Length - 1 To 0 Step -1
procesos(i).Kill()
Next
End If
End Sub
If you put the kill process method right after the print method you won't get your document printed (I guess this is because process is killed before it is sent to printer). So, between these 2 methods, I added this line:
Threading.Thread.Sleep(10000) ' 10000 is the milisecs after the next code line is executed
And with this my code worked as I wanted. Hope it helps you!

Using images stored in Zebra printer to create a label in vb.net

Is there any way to use the images stored in a Zebra printer in the following code:
Dim g As Graphics = e.Graphics
Dim bc As New BarcodeProfessional
Dim br As Brush = New SolidBrush(Drawing.Color.Black)
Dim blackPen As New Pen(Color.Black, 5)
e.Graphics.DrawArc(blackPen, 10, 10, 70, 50, 130, 100)
g.DrawString("UPC", Arial_6_bold, br, 210, 15)
the above prints an arc, and a "UPC" text, now can I print here also an image stored in the Zebra printer?
I have found that I can send ZPL code to the printer in this way:
Dim ipAddress As String = "10.3.14.59"
Dim port As Integer = 9100
Dim ZPLString As String = _
"^XA" & _
"^FO50,50" & _
"^A0N,50,50" & _
"^FDHello, World!^FS" & _
"^XZ"
Try
'Open Connection
Dim client As New System.Net.Sockets.TcpClient
client.Connect(ipAddress, port)
'Write ZPL String to Connection
Dim writer As New System.IO.StreamWriter(client.GetStream())
writer.Write(ZPLString)
writer.Flush()
'Close Connection
writer.Close()
client.Close()
Catch ex As Exception
'Catch Exception Here
End Try
But I don't know how to put together both codes, any idea?
If the graphic will be static and doesn't change based on user input or etc., you could just create a .grf out of it. I guess the easiest way to do that would be to export the image as a bitmap, open in paint, save as a .pcx file, and then open it in ZTools to convert to a hex .grf file. Then you can send the graphic to the printer along with your other ZPL code.
For examples on how to do this, I'll refer you to the ZPL programming guide, available at http://www.servopack.de/support/zebra/ZPLbasics.pdf
You'll find an example that explains creating and printing .grf files on page 36, and an example of sending both .grf and text to a label on page 63.
It sounds like your image is already stored to the printer. If so, its file name (as stored on the printer) should be something like 'E:MYFILE.GRF'. You can use the ZPL command ^XG to recall stored graphics. So, by sending the following ZPL, the graphic should print after the text 'Hello, World!":
"^XA" & _
"^FO50,50" & _
"^A0N,50,50" & _
"^FDHello, World!^FS" & _
"^XGE:MYFILE.GRF,1,1^FS" & _
"^XZ"
In case your image isn't already stored, you can store a GRF file through the ~DY command, but it is far easier to download objects through Zebra Setup Utilities: http://www.zebra.com/us/en/products-services/software/manage-software/zebra-setup-utility.html.
Source: https://support.zebra.com/cpws/docs/zpl/zpl_manual.pdf.

Printing with Brother SDK to Brother Network Shared Printer

I am developing with vb.net to print barcode label using Brother Printer PT 98OOPCN. I am using Network Shared, not Peer to Peer.
There is my code
Dim objDoc As bpac.Document
objDoc = CreateObject("bpac.Document")
Dim PrinterName As String = "\\hostprinterserver\printer1"
If (objDoc.Open("Label_Barcode\Label_Ex.lbx")) Then
objDoc.GetObject("dateObject").Text = "10/23/2012"
objDoc.GetObject("barcodeObject").Text = "100123239734"
objDoc.SetPrinter(PrinterName, True)
objDoc.StartPrint("", PrintOptionConstants.bpoDefault)
objDoc.PrintOut(1, PrintOptionConstants.bpoDefault)
objDoc.EndPrint()
objDoc.Close()
End If
Is it possible to print with Brother SDK to Network Shared Printer?
if it is possible how to do that think?
Dim PrinterName As String = "printer1 on hostprinterserver'sIP"
For instance:
Dim PrinterName As String = "Brother PT-9600 on 192.168.1.45"
It worked for me!