Basic Xamarin Print Example

Hi Everyone,

We've gotten several requests for some basic sample code for the Link-OS Multiplatform SDK showing it's use with Xamarin.

First, you need to install the SDK, either by downloading it from Zebra.com and following the install instructions, or getting it directly from Nuget. Full API documentation is on Link-OS SDK - Zebra Technologies Techdocs .

The sample code creates an app with a text box for entering a printer address and a print button.  When you press the print button, the words "Hello World" print on your Zebra Printer. The address can be an IP address or a Bluetooth MAC address for your printer.

This sample code is for Android, but you can copy the printing portions into an iOS or Forms app without changes.  I gave permissions for BLUETOOTH and BLUETOOTH_ADMIN in the manifest.  As a note, this code will set your printer to ZPL mode, so if you want to your app to print in line mode, you will need to change it back or modify the code.   If you just want to test this code over Bluetooth, you can speed up time to print by changing the connection builder string to

connection = ConnectionBuilder.Current.Build("BT:" + address);

Happy Coding!

MainActivity.cs

/***********************************************

CONFIDENTIAL AND PROPRIETARY

The source code and other information contained herein is the confidential and the exclusive property of

ZIH Corp. and is subject to the terms and conditions in your end user license agreement.

Copyright ZIH Corp. 2016

ALL RIGHTS RESERVED

***********************************************/

using System;

using Android.App;

using Android.Widget;

using Android.OS;

using System.Threading.Tasks;

using LinkOS.Plugin.Abstractions;

using LinkOS.Plugin;

using Android.Util;

using System.Text;

namespace BasicPrint

{

    [Activity(Label = "BasicPrint", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity

    {

        Button button;

        EditText addressTxt;

        const string tag = "BasicPrintApp";

        IConnection connection;

        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle);

            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,

            // and attach an event to it

            button = FindViewById<Button>(Resource.Id.MyButton);

            addressTxt = FindViewById<EditText>(Resource.Id.address);

            connection = null;

            button.Click += delegate {

                Start_Print();

            };

        }

        private void Start_Print()

        {

            button.Enabled = false;

            string address = addressTxt.Text;

            // Bluetooth communications must be handled on a separate thread and it's

            //    best practice to handle network coms on it as well

            new Task(() =>

            {

                Print(address);

            }).Start();

        }

        private void Print(string address)

        {

            string zpl = "^XA^LL200^FO30,20^A0N,30,30^FDHello World^FS^XZ";

            try

            {

                if ((connection == null) || (!connection.IsConnected))

                {

                    connection = ConnectionBuilder.Current.Build(address);

                    connection.Open();

                }

                if ((SetPrintLanguage(connection)) && (CheckPrinterStatus(connection)))

                {

                    connection.Write(Encoding.ASCII.GetBytes(zpl));

                }

            }

            catch (Exception e)

            {

                //if the device is unable to connect, an exception is thrown

                Log.Debug(tag, e.ToString());

            }

            finally

            {

                this.RunOnUiThread(() =>

                {

                    button.Enabled = true;

                });

            }

        }

        private bool SetPrintLanguage(IConnection connection)

        {

            string setLanguage = "! U1 setvar \"device.languages\" \"zpl\"\r\n\r\n! U1 getvar \"device.languages\"\r\n\r\n";

            byte[] response = connection.SendAndWaitForResponse(Encoding.ASCII.GetBytes(setLanguage), 500, 500);

            string s = Encoding.ASCII.GetString(response);

            if (!s.Contains("zpl"))

            {

                Log.Debug(tag, "Not a ZPL printer.");

                return false;

            }

            return true;

        }

        private bool CheckPrinterStatus(IConnection connection)

        {

            IZebraPrinter printer = ZebraPrinterFactory.Current.GetInstance(PrinterLanguage.ZPL, connection);

            IPrinterStatus status = printer.CurrentStatus;

            if (! status.IsReadyToPrint)

            {

                Log.Debug(tag, "Printer in Error: " + status.ToString());

            }

            return true;

        }

        protected override void OnPause()

        {

            base.OnPause();

            Log.Debug(tag, "Closing connection on inactive app");

            if ((connection != null) && (connection.IsConnected))

            {

                connection.Close();

            }

        }

    }

}

Main.axml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/address"

        android:hint="@string/Address" />

    <Button

        android:id="@+id/MyButton"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="@string/Hello" />

</LinearLayout>

Robin West

Solution Architect

Zebra Technologies

Anonymous (not verified)

Hi Allen, I'm not sure on that one, I was also going to suggest Multidex as well as that fixed the "code 2" issue when I've run into it. Looks like this second error might have something to do with your JDK version.  Some of the other notes seemed to indicate you can fix it by updating Proguard.

44187 – Build error when Proguard or MultiDex options are enabled

"Unsupported class version number [52.0]" build error — Xamarin Forums


Allen Lukowitz

Hi Robin,

What happened to this thread? I was getting back to looking at the code and wanted to check how to add the mpsdk to my visual studio project it was gone?

Thank you

al


Allen Lukowitz

Thanks Robin,

I was looking for this example you posted

https://developer.zebra.com/community/technologies/printers/label-printe...

I was also looking for the instruction on how to add the Link OS to a Visual Studio C# project. I have already downloaded it to my PC

Thanks again

al

Allen G. Lukowitz

Director of Technical Services

CaraFlow LLC

414-906-9170

alukowitz@caraflow.com<mailto:alukowitz@caraflow.com>

<http://www.caraflow.com/>


Anonymous (not verified)

Hi Allen, Over the weekend we "streamlined" the site and moved a lot of the content around.  If you are looking for something please use search, or reply with your original link and I'll find and post the new one.


Petre Dita

hello

i need to write on a ZQ110 thermal printer

i am trying the simple version of this sample

connection = LinkOS.Plugin.ConnectionBuilder.Current.Build(address); //<<< ISSUE HERE

                      connection.Open();

                    connection.Write(Encoding.ASCII.GetBytes("^XA^PW800^LL200^FO30,30^A0N,30,30^FDHello World!!!^FS^XZ"));

the result is that it prints exactly this string: "^XA^PW800^LL200^FO30,30"

on the second try it prints the rest: "^A0N,30,30^FDHello World!!!^FS^XZ"

SetPrintLanguage returns ""

CheckPrinterStatus returns error "malformed unknown printer"

any help would be apreciated


Anonymous (not verified)

Hi Petre, The ZQ110 is one of the few Zebra printers that will not work with the Link-OS SDKs in any way.  Please see the ZQ110 specific SDK's on the support page: ZQ110 Mobile Printer Support & Downloads | Zebra


Petre Dita

Hello Robin,

I have bought ZQ310

my question is: can i use a label generated from Zebra designer with linkos?

thanks


Jose Espinoza

Hi Robin West, Thanks for your code, I used and works excellent.

I Try to add more lines, but I only can print 4 3 more lines, after that stop printing. We are using and iMZ320

Can You help us?

Thanks


Rachel Susairaj

Hi,

connection = ConnectionBuilder.Current.Build(addr);  

We are using  Zebra QLn220 printer. 

In the sample code, the above line takes about 6 seconds to execute. Hence the printing time is approx 6 seconds due to the above line. Is there any way, we can improve the speed here ?

Thanks,


Giovanni Pantano

Hi

I have a problem with the connection by wifi when making the conection.open I generated the following error could help me

{Zebra.Sdk.Comm.ConnectionException: Could not open connection

  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <fcbf47a04b2e4d90beafbae627e1fca4>:0

  at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method) [0x00068] in <3cb12bce834a498199b2be6cd3e00922>:0

  at Android.Runtime.JNIEnv.CallVoidMethod (System.IntPtr jobject, System.IntPtr jmethod) [0x0000e] in <ff199c98c3f84852925dd37a0ef6113a>:0

  at Zebra.Sdk.Comm.MultichannelConnection.Open () [0x00044] in C:\Users\jvanhuis\source\repos\xamarin-sdk\Binding Libraries\ZSDK_ANDROIDX\ZSDK_ANDROIDX\obj\Debug\generated\src\Zebra.Sdk.Comm.MultichannelConnection.cs:569

  at LinkOS.Plugin.ConnectionImplementation.Open () [0x00001] in C:\Users\jvanhuis\source\repos\xamarin-sdk\Link_OS_SDK_for_Xamarin_Portable\LinkOS\LinkOS.Plugin.Android\ConnectionImplementation.cs:106

  at LabelBunch.ViewModels.VariViewModels.PrintLineMode () [0x00010] in G:\proyectos\Labelbunch\LabelBunch\LabelBunch\LabelBunch\ViewModels\VariViewModels.cs:166

  --- End of managed Zebra.Sdk.Comm.ConnectionException stack trace ---

com.zebra.sdk.comm.ConnectionException: Could not open connection

at com.zebra.sdk.comm.MultichannelConnection.open(Unknown Source)

at md5270abb39e60627f0f200893b490a1ade.ButtonRenderer_ButtonClickListener.n_onClick(Native Method)

at md5270abb39e60627f0f200893b490a1ade.ButtonRenderer_ButtonClickListener.onClick(ButtonRenderer_ButtonClickListener.java:30)

at android.view.View.performClick(View.java:5273)

at android.view.View$PerformClick.run(View.java:21315)

at android.os.Handler.handleCallback(Handler.java:743)

at android.os.Handler.dispatchMessage(Handler.java:95)

at android.os.Looper.loop(Looper.java:150)

at android.app.ActivityThread.main(ActivityThread.java:5665)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)

}


Mauro Carta

Hello Robin,

I need your kind help.

I'm using your example with LinkOS_Xamarin_SDK 1.2; sometimes I receive communication error or broken pipe error while printing on bluetooth ZPL printer.

For this reason I wanna try new Zebra.Printer.SDK 2.15, but unfortunately your example doesn't work anymore.

For example, there isn't any "IConnection" interface.

(IConnection connection;  )

Could you tell me where can I found a example (old xamarin android, not forms!) ?

Regards,

Mauro