Printing with Zebra Link-Os SDK - c#

I am using this code to print an image to a zebra printer.
ZebraPrinterConnection connection = new TcpPrinterConnection(ipAddress,port);
connection.Open();
ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);
printer.GetGraphicsUtil().PrintImage("imageAddress");
It works fine but some times the printer doesn't print and in the code I dont get any errors. Is there a way to check if physically the label was printed?

There are a couple of ways to do this.
First way is to check the status during/after you print and confirm there are no bytes in the buffer and no error on the printer:
private boolean postPrintCheckPrinterStatus(Connection connection)
{
ZebraPrinter printer = ZebraPrinterFactory.getInstance(PrinterLanguage.ZPL, connection);
PrinterStatus printerStatus = printer.getCurrentStatus();
// loop while printing until print is complete or there is an error
while ((printerStatus.numberOfFormatsInReceiveBuffer > 0) && (printerStatus.isReadyToPrint))
{
printerStatus = printer.getCurrentStatus();
}
if (printerStatus.isReadyToPrint) {
System.out.println("Ready To Print");
return true;
} else if (printerStatus.isPaused) {
System.out.println("Cannot Print because the printer is paused.");
} else if (printerStatus.isHeadOpen) {
System.out.println("Cannot Print because the printer head is open.");
} else if (printerStatus.isPaperOut) {
System.out.println("Cannot Print because the paper is out.");
} else {
System.out.println("Cannot Print.");
}
return false;
}
The other way to check this would be to use the printer odometer to ensure the label was printed. Check the odometer before and then again after:
// Set settings, check status, print, etc.
if (setPrintLanguage(statusConnection) && checkPrinterStatus(statusConnection))
{
int labelCount = Integer.parseInt(SGD.GET("odometer.total_label_count", statusConnection));
// Send Print Job (1 label)
String zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";
printerConnection.write(zplData.getBytes());
if (postPrintCheckPrinterStatus(statusConnection))
{
int newLabelCount = Integer.parseInt(SGD.GET("odometer.total_label_count", statusConnection));
if (newLabelCount == labelCount + 1)
{
System.out.println("Print Successful.");
}
}
//else reprint?
}

Please try with following code:
id<GraphicsUtil, NSObject> graphicsUtil = [zebraPrinter getGraphicsUtil];
UIImage* image = [UIImage imageNamed:#"ImageName"];
BOOL success = [graphicsUtil printImage:[image CGImage] atX:155 atY:0 withWidth:200 withHeight:80 andIsInsideFormat:NO error:&error];
if(error) {
NSLog(#"ERROR: %#", error);
}

Related

Why I am printing XPS file to receipt printer but get raw file content on paper instead?

I am trying to print out a XPS file to my receipt printer (EPSON TM-T88IV Receipt). I am using PrintQueue to print the document which is read from a memory stream. It works well at most of times, but sometimes, it prints out the raw file content instead of what it should be.
Here is my code for printing XPS:
public class XpsPrinterHelper
{
public bool Print(byte[] documentImage, string printerName, string tempXpsFilename = "report.xps")
{
var success = false;
var thread = new Thread(() =>
{
using (var printerQueue = GetPrintQueueFromPrinterName(printerName))
{
try
{
//save file temporary
var filename = Path.Combine(Directory.GetCurrentDirectory(), tempXpsFilename);
File.WriteAllBytes(filename, documentImage);
using (var printSystemJobInfo = printerQueue.AddJob())
{
printSystemJobInfo.JobStream.Write(documentImage, 0, documentImage.Length);
}
success = true;
}
catch (PrintJobException)
{
printerQueue.Dispose();
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join(); //Wait until finished
return success;
}
private static PrintQueue GetPrintQueueFromPrinterName(string printerName)
{
if (printerName.StartsWith(#"\\")) //If it is a shared printer
{
var serverPath = printerName.Substring(0, printerName.LastIndexOf('\\'));
var sharedPrinterName = printerName.Replace(serverPath, "");
var printServer = new PrintServer(serverPath.TrimEnd('\\'));
return printServer.GetPrintQueue(sharedPrinterName.Trim('\\'));
}
var localPrintServer = new LocalPrintServer();
return localPrintServer.GetPrintQueue(printerName);
}
}
But sometimes the result likes a trash
I really appreciate anyone point out what happened or give me suggestion to solve this issue.

Change Image in Update With NFC (Clear Android Intent Issue)

I have the next code:
void Update ()
{
if (Application.platform == RuntimePlatform.Android)
{
if(!already_switched){
try
{
// Create new NFC Android object
AndroidJavaObject mActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"); // Activities open apps
mIntent = mActivity.Call<AndroidJavaObject>("getIntent");
string sAction = mIntent.Call<String>("getAction"); // resulte are returned in the Intent object
if (sAction == "android.nfc.action.NDEF_DISCOVERED")
{
Debug.Log("Tag of type NDEF");
}
else if (sAction == "android.nfc.action.TECH_DISCOVERED")
{
GetComponent<ButtonScrollingUp>().actual_pos = GetComponent<ButtonScrollingUp>().actual_pos + 1;
if (GetComponent<ButtonScrollingUp>().actual_pos > GetComponent<ButtonScrollingUp>().images.Count) GetComponent<ButtonScrollingUp>().actual_pos = 0;
image.GetComponent<SpriteRenderer>().sprite = GetComponent<ButtonScrollingUp>().images[GetComponent<ButtonScrollingUp>().actual_pos];
text_.GetComponent<Text>().text = GetComponent<ButtonScrollingUp>().texts[GetComponent<ButtonScrollingUp>().actual_pos];
return;
}
else if (sAction == "android.nfc.action.TAG_DISCOVERED")
{
tag_output_text.text += "Not supported";
}
else
{
tag_output_text.text = "Scan a NFC tag to make the cube disappear...";
return;
}
}
catch (Exception ex)
{
string text = ex.Message;
tag_output_text.text = text;
}
}
}
}
The code change an image when a NFC get close to the phone, the problem is that it changes the image one time per frame. I could do it just to change one time, but I don't want that, I want that each time that someone get close the NFC it changes. I think that I could solve that if I clear the intent stack, and I can do it with this:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
But I don't know how to do that in c# and unity.
Could someone help me?
I think that I could solve that if I clear the intent stack, and I can
do it with this:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
But I don't know how to do that in c# and unity.
You already have the intent stored in the mIntent variable:
AndroidJavaObject mActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"); // Activities open apps
AndroidJavaObject mIntent = mActivity.Call<AndroidJavaObject>("getIntent");
To get the equivalent of the Java code below:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
First, get the Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_CLEAR_TASK int values in C# from the Intent:
int FLAG_ACTIVITY_NEW_TASK = mIntent.GetStatic<int>("FLAG_ACTIVITY_NEW_TASK");
int FLAG_ACTIVITY_CLEAR_TASK = mIntent.GetStatic<int>("FLAG_ACTIVITY_CLEAR_TASK");
Now, you can do the bitwise operation and pass them to the setFlags function:
int orOP = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK;
mIntent.Call<AndroidJavaObject>("setFlags", orOP);
Maybe something like this:

How to check each line from an website/php file and Enable/disable Components C#

I try to make a function that allows me to enable and disable multiple components from a server. Preferably from one php file.
Example:
Website Side
AdminPanelEnabled=True
UserIPPanelEnabled=False
GuestPanelEnabled=True
(On the website there is no other code just what you see above)
If it is set to true on the server/website it will enable the component or if set to false it will disable the component.
Tries and fails
Checker = new WebClient().DownloadString("URL/Checker.php");
if (Checker == "AdminPanelEnabled=True")
{
AdminPanel.Enabled = true;
}
else
{
AdminPanel.Enabled = false;
}
if (Checker == "UserIPPanelEnabled=True")
{
UserIPPanel.Enabled = true;
}
else
{
UserIPPanel.Enabled = false;
}
if (Checker == "GuestPanelEnabled=True")
{
GuestPanel.Enabled = true;
}
else
{
GuestPanel.Enabled = false;
}
The file you provided consists of multiple lines, so you have to separate the lines first and then check every single line. So, maybe something like this works?
string[] lines = new WebClient().DownloadString("Checker.php")
.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines)
{
string[] config = line.Split('=');
if (config[0] == "AdminPanelEnabled")
{
AdminPanel.Enabled = bool.Parse(config[1]);
}
else if (config[0] == "UserIPPanelEnabled")
{
UserIPPanel.Enabled = bool.Parse(config[1]);
}
else if (config[0] == "GuestPanelEnabled")
{
GuestPanel.Enabled = bool.Parse(config[1]);
}
}

PosPrinter GetDefaultAsync always returns null

I'm trying to print a ticket using .NET POS but i'm not able to get the Default printer.
PosPrinter defaultPrinter = await PosPrinter.GetDefaultAsync();
I also tried this:
string deviceSelector = PosPrinter.GetDeviceSelector();
PosPrinter printer = await PosPrinter.FromIdAsync(deviceSelector);
I have my thermal printer configured as default.
Have you tried the way using the PosExplorer and the printer name? Snippet:
public PosPrinter GetPrinterByName(System.Windows.Forms.Form mainForm, string printerName)
{
PosPrinter printer = null;
PosExplorer explorer = new PosExplorer(mainForm);
DeviveCollection printers = explorer.GetDevices(DeviceType.PosPrinter);
if (printers != null && printers.Count > 0)
{
for (int i = 0; i < printers.Count; i++)
{
if(0 == string.Compare(printerName, printers[i].ServiceObjectName))
{
printer = printers[i];
break;
}
}
}
return printer;
}

Using ManagementObjectSearcher and Win32_Printer to check Status

I have been forced to use the RawPrinterHelper class to print to a thermal printer because the PrintDocument method has proven unfit for POS printing.
I now need to check the status of the printer prior to printing to be sure that it is, online and ready to print. I have been able to successful check attributes from Win32_Printer. I can see properties such as PrinterStatus, changing from 3, to a 2 or a 1 when out of paper or tray is open. This is great.
My question is, which properties should indicate it is O.K. to print? There must be more than just checking if PrinterStatus is idle (3).
private bool ReadyCheck(string printerName)
{
bool ready = false;
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
// Print status = 3, idle and ready to print
string status = printer.Properties["PrinterStatus"].Value.ToString();
string extendedPrinterStatus = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
// What else means printer is ready?
if (status.Trim() == "3")
ready = true;
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
return ready;
}
Edit:
#vendettamit Sorry I didn't ask very well. For instance, Idle (3) indicates it's OK to print. I am wondering if there are more which also indicate it's OK to print such as; Printing (4), WarmUp (5), ect, or is Idle (3) the only time you should send the next print job? Thanks
Below are the values that you can take into account to check if It's ready to print:
Other (1)
Unknown (2)
Idle (3)
Printing (4)
Warmup (5)
Stopped Printing (6)
Offline (7)
Also a note from Remarks on MSDN documentation for Win32_Printer-
If you are retrieving PrinterStatus = 3 or PrinterState = 0, the printer driver may not be feeding accurate information into WMI. WMI retrieves the printer information from the spoolsv.exe process. It is possible the printer driver does not report its status to the spooler. In this case, Win32_Printer reports the printer as Idle.
**//check printer is online**
private static bool IsOnline(ManagementBaseObject printer)
{
bool isOnlineprinter = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var ResultPrinter01 = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
var ResultPrinter02 = printer.Properties["PrinterState"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(no internet connection or printer switched off):PrinterState
if (ResultPrinter02 == "128"|| ResultPrinter02=="4096")
{
isOnlineprinter = false;
}
////printer is initializing....
//if (ResultPrinter02 == "16")
//{
// isOnlineprinter = false;
//}
//(no internet connection or printer switched off):ExtendedPrinterStatus
if (ResultPrinter01 == "7")
{
isOnlineprinter = false;
}
}
return isOnlineprinter;
}
**//check for out of paper**
private static bool IspaperOK(ManagementBaseObject printer)
{
bool PaperOK = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var PaperStatus = printer.Properties["PrinterState"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)16 = Out of Paper
//(PrinterState)5 = Out of paper
//(PrinterState)4 = paperjam
//(PrinterState)144 = Out of paper
if ((PaperStatus == "5") || (PaperStatus == "16")||(PaperStatus=="144"))
{
PaperOK = false;
}
}
return PaperOK;
}
**//Verify still printing state or not**
private static bool Isprinting(ManagementBaseObject printer)
{
bool Isprintingnow = false;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var printing01 = printer.Properties["PrinterState"].Value.ToString();
var printing02 = printer.Properties["PrinterStatus"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)11 = Printing
//(PrinterState)1024 = printing
//(PrinterStatus)4 = printing
if (printing01 == "11" || printing01 == "1024" || printing02=="4")
{
Isprintingnow = true;
}
}
return Isprintingnow;
}
**//check for error (Printer)**
private static bool IsPrinterError(ManagementBaseObject printer)
{
bool PrinterOK = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var PrinterSpecificError = printer.Properties["PrinterState"].Value.ToString();
var otherError = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)2 - error of printer
//(PrinterState)131072 - Toner Low
//(PrinterState)18 - Toner Low
//(PrinterState)19 - No Toner
if ((PrinterSpecificError == "131072")||(PrinterSpecificError == "18")||(PrinterSpecificError == "19")||(PrinterSpecificError == "2")||(PrinterSpecificError == "7"))
{
PrinterOK = false;
}
//(ExtendedPrinterStatus) 2 - no error
if (otherError=="2")
{
PrinterOK = true;
}
else
{
PrinterOK = false;
}
}
return PrinterOK;
}
**//check Network or USB**
private static bool IsNetworkPrinter(ManagementBaseObject printer)
{
bool IsNetwork = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var network = printer.Properties["Network"].Value.ToString();
var local = printer.Properties["Local"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
if (network == "True")
{
IsNetwork = true;
}
if (network == "True" && local == "True")
{
IsNetwork = true;
}
if (local == "True" && network=="False")
{
IsNetwork = false;
}
}
return IsNetwork;
}
//(PrinterState)16 = Out of Paper
//(PrinterState)5 = Out of paper
//(PrinterState)4 = paperjam
//(PrinterState)144 = Out of paper
//(PrinterState)4194432 = Lid Open
//(PrinterState)4194448 = Out of paper/Lid open
//(PrinterState)4096= Offline
//(PrinterState)1024= Printing
//(PrinterState)128= Printer is offline

Categories