How to connect bluetooth printer with Xamarin.Forms – Chapter 1 Android

Follow the comments and you can download source code here.

    /// <summary>
    /// We need to create an interface for DependencyService (Android-iOS-UWP)
    /// </summary>    
    public interface IBlueToothService
    {
        IList<string> GetDeviceList();
        Task Print(string deviceName, string text);
    }

Simple ViewModel

public class PrintPageViewModel
    {
        private readonly IBlueToothService _blueToothService;

        private IList<string> _deviceList;
        public IList<string> DeviceList
        {
            get
            {
                if (_deviceList == null)
                    _deviceList = new ObservableCollection<string>();
                return _deviceList;
            }
            set
            {
                _deviceList = value;
            }
        }

        private string _printMessage;
        public string PrintMessage
        {
            get
            {
                return _printMessage;
            }
            set
            {
                _printMessage = value;
            }
        }

        private string _selectedDevice;
        public string SelectedDevice
        {
            get
            {
                return _selectedDevice;
            }
            set
            {
                _selectedDevice = value;
            }
        }

        /// <summary>
        /// Print text-message
        /// </summary>
        public ICommand PrintCommand => new Command(async () =>
        {
            PrintMessage += " Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
            await _blueToothService.Print(SelectedDevice, PrintMessage);
        });

        public PrintPageViewModel()
        {
            _blueToothService = DependencyService.Get<IBlueToothService>();
            BindDeviceList();
        }

        /// <summary>
        /// Get Bluetooth device list with DependencyService
        /// </summary>
        void BindDeviceList()
        {
            var list = _blueToothService.GetDeviceList();
            DeviceList.Clear();
            foreach (var item in list)
                DeviceList.Add(item);
        }
    }

Simple Page

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodels="clr-namespace:BlueToothPrinter.ViewModels;assembly=BlueToothPrinter"
             x:Class="BlueToothPrinter.Pages.PrintPage">
    <ContentPage.BindingContext>
        <viewmodels:PrintPageViewModel />
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Picker ItemsSource="{Binding DeviceList}"
                    Title="Select Device"
                    ItemDisplayBinding="{Binding .}"
                    SelectedItem="{Binding SelectedDevice}" />
            <Entry Text="{Binding PrintMessage}"
                   Placeholder="Message"/>
            <Button Text="Print"
                    Command="{Binding PrintCommand}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
[assembly: Xamarin.Forms.Dependency(typeof(AndroidBlueToothService))]
namespace BlueToothPrinter.Droid.DependencyServices
{
    class AndroidBlueToothService : IBlueToothService
    {
        /// <summary>
        /// We have to use local device Bluetooth adapter.
        /// BondedDevices returns BluetoothDevice collection anyway I need to take just device name.
        /// </summary>
        /// <returns></returns>
        public IList<string> GetDeviceList()
        {
            using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
            {
                var btdevice = bluetoothAdapter?.BondedDevices.Select(i => i.Name).ToList();
                return btdevice;
            }
        }

        /// <summary>
        /// We have to use local device Bluetooth adapter.
        /// We need to find Bluetooth Device with selected device name.
        /// Now, we use BluetoothSocket class with most common UUID
        /// Try to connect BluetoothSocket then convert your text-message to bytearray
        /// Last step write your bytearray by way of bluetoothSocket
        /// </summary>
        /// <param name="deviceName">Selected deviceName</param>
        /// <param name="text">My printed text-message</param>
        /// <returns></returns>
        public async Task Print(string deviceName, string text)
        {
            using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
            {
                BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
                                          where bd?.Name == deviceName
                                          select bd).FirstOrDefault();
                try
                {
                    using (BluetoothSocket bluetoothSocket = device?.
                        CreateRfcommSocketToServiceRecord(
                        UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
                    {
                        bluetoothSocket?.Connect();
                        byte[] buffer = Encoding.UTF8.GetBytes(text);
                        bluetoothSocket?.OutputStream.Write(buffer, 0, buffer.Length);
                        bluetoothSocket.Close();
                    }
                }
                catch (Exception exp)
                {
                    throw exp;
                }
            }
        }
    }
}

Chapter 2 iOS then UWP

Yiğit

Xamarin Developer, Consultant & Architect. Community Leader and Director of Xamarin Türkiye

14 Comments

You can post comments in this post.


  • Thanks for post, i want to know how do that in IOS
    How to connect bluetooth printer with Xamarin.Forms – Chapter 2

    Vianey Santuario 5 sene ago Reply


  • thank´s i want see second part

    Vianey Santuario 5 sene ago Reply


  • Hello.
    Thanks for your great article.
    Can you help me to print Vietnamese language?
    Because the Vietnamese word has the above sign
    For example: Đam mê lập trình
    thank you.

    Nguyễn Xuân Huy 5 sene ago Reply


    • Hi, I can try Vietnamese words in few days.

      Yiğit 5 sene ago Reply


      • Hello
        “Hi, I can try Vietnamese words in few days.”
        ==> Can you help me with the Vietnamese print topic?
        I am very happy when someone can help me.
        I really need it.

        Nguyễn Xuân Huy 5 sene ago Reply


  • Where is the chapter 2????

    Vladimir 5 sene ago Reply


    • in June ^^

      Yiğit 5 sene ago Reply


  • Hey… do you how can i print my text in this way, but changing font size of my string and placing bold text in the string?

    Waiting for answer,

    Regards.

    Gabriel Mendez 4 sene ago Reply


    • Try to use html tags like

      Yiğit 4 sene ago Reply


  • Works to print PDF also?

    Eduardo Quiroz 4 sene ago Reply


    • I didn’t try to print PDF but If you can convert pdf to text I think It will work

      Yiğit 4 sene ago Reply


  • Merhaba
    Türkçe karakterler için UTF8 yerine iso-8859-9 denediğimizde çalışmıyor.Xamarinde bunu çözmenin bir yolu var mı acaba ?

    ibrahim 4 sene ago Reply


    • UTF8 yerine neden iso-8859-9?

      Yiğit 4 sene ago Reply


  • IOS kısmı niye gelemedi hocam? Neredeyse hiç örnek yok bu konuda.

    Ömer 2 sene ago Reply


Post A Reply