Reputation: 1
Im developing an application that prints an image of a voucher in a Zebra heath printer via bluetooth using SkiaSharp (2.88.5) and SkiaSharp.Views.Forms (2.88.5) to generate the voucher image and ShinyBluetoothLE (2.7.3) to print that image via bluetooth in Xamarin Forms, but when printing, instead of the voucher image I get a bunch of random characters. What am I doing wrong? Is something missing from my code?
MainViewModel.cs
using BluetoothTest.Interfaces;
using BluetoothTest.Model;
using SkiaSharp;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace BluetoothTest.ViewModel
{
public class MainViewModel : BaseViewModel
{
byte[] globalImageByte = null;
/*000000000000000000000000000000000000000000000000000000000000000000000000000*/
public ICommand PrintCommand { get; protected set; }
public string selectedDevice;
/*000000000000000000000000000000000000000000000000000000000000000000000000000*/
public List<string> pairedDevices;
/*000000000000000000000000000000000000000000000000000000000000000000000000000*/
private Voucher_Model _voucher;
public Voucher_Model Voucher
{
get { return _voucher; }
set { _voucher = value; OnPropertyChanged(); }
}
private SKSurface _surface;
public SKSurface Surface
{
get { return _surface; }
}
/*000000000000000000000000000000000000000000000000000000000000000000000000000*/
public MainViewModel()
{
_voucher = new Voucher_Model()
{
Customer = "Edgar Allan Poe",
Date = "20/08/2023",
Detalles = new List<Detalle_Model>()
{
new Detalle_Model()
{
Product = "Product 1",
Price = 100
},
new Detalle_Model()
{
Product = "Product 2",
Price = 200
},
}
};
// Initialize the command
PrintCommand = new Command(Prntbutton_Clicked);
GetDeviceList();
//Crear comando que ejecute la seleccion de dispositivo
}
/*000000000000000000000000000000000000000000000000000000000000000000000000000*/
private List<string> GetDeviceList()
{
IPrintService service = DependencyService.Get<IPrintService>();
var getDeviceList = service.GetDeviceList();
if (getDeviceList == null)
return null;
if (getDeviceList.Count == 0)
{
App.Current.MainPage.DisplayAlert("Alert", "No Bluetooth Device found", "Ok");
return null;
}
else
{
pairedDevices = new List<string>(getDeviceList);
return pairedDevices;
}
}
public async Task<byte[]> GenerateVoucher(object sender, SkiaSharp.Views.Forms.SKPaintGLSurfaceEventArgs e)
{
SKSurface surface = e.Surface;
SKCanvas canvas = surface.Canvas;
SKPaint paint = new SKPaint();
/*Config*/
paint.Color = SKColors.Black;
paint.TextSize = 30;
// Draw the background
canvas.Clear(SKColors.WhiteSmoke);
// Draw the client name
canvas.DrawText($"Customer: {Voucher.Customer}", new SKPoint(10, 40), paint);
// Draw the date
canvas.DrawText($"Date: {Voucher.Date}", new SKPoint(10, 80), paint);
// Draw the list of details
int index = 0;
foreach (var detalle in _voucher.Detalles)
{
// Draw the product name
canvas.DrawText(detalle.Product, new SKPoint(10, 160 + 20 * index), paint);
// Draw the price
canvas.DrawText(detalle.Price.ToString("C"), new SKPoint(250, 160 + 20 * index), paint);
index++;
}
// Convert the canvas to an SKData
var image = surface.Snapshot();
var skdata = image.Encode(SKEncodedImageFormat.Png, 100);
//Convert skdata to byteArray;
var data = skdata.ToArray();
globalImageByte = data;
// Return the byte array
return data;
}
public async void Prntbutton_Clicked()
{
var sel_device = Preferences.Get("SelectedDevice", "");
IPrintService service = DependencyService.Get<IPrintService>();
await service.Print(sel_device, globalImageByte);
globalImageByte = null;
}
}
}
BluetoothServiceRenderer.cs (in Android project)
using Android.Bluetooth;
using BluetoothTest.Droid.Services;
using BluetoothTest.Interfaces;
using Java.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
[assembly: Xamarin.Forms.Dependency(typeof(BluetoothServiceRenderer))]
namespace BluetoothTest.Droid.Services
{
public class BluetoothServiceRenderer : IPrintService
{
public IList<string> GetDeviceList()
{
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
var btdevice = bluetoothAdapter?.BondedDevices.Select(i => i.Name).ToList();
return btdevice;
}
}
public async Task Print(string deviceName, byte[] imgbyte)
{
BluetoothDevice myDevice;
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
myDevice = (from bd in bluetoothAdapter?.BondedDevices
where bd?.Name == deviceName
select bd).FirstOrDefault();
}
try
{
using (BluetoothSocket bluetoothSocket = myDevice?.
CreateRfcommSocketToServiceRecord(
UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
{
bluetoothSocket?.Connect();
byte[] buffer = imgbyte;
bluetoothSocket?.OutputStream.Write(buffer, 0, buffer.Length);
bluetoothSocket.Close();
}
}
catch (Exception exp)
{
throw exp;
}
}
}
}
IPrintService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BluetoothTest.Interfaces
{
public interface IPrintService
{
IList<string> GetDeviceList();
Task Print(string deviceName, byte[] imgByte);
}
}
VoucherPreview_Page.xaml
<?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:skia ="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
x:Class="BluetoothTest.View.VoucherPreview_Page">
<ContentPage.Content>
<StackLayout VerticalOptions="CenterAndExpand">
<Picker WidthRequest="250"
HeightRequest="50"
HorizontalOptions="CenterAndExpand"
x:Name="MyDevices"
SelectedIndexChanged="MyDevicePicker_SelectedIndexChanged"
Title="Selecionar Impresora"
ItemDisplayBinding="{Binding .}"/>
<ScrollView>
<skia:SKGLView x:Name="voucherImage"
HeightRequest="700"
WidthRequest="400"
PaintSurface="canvasView_PaintSurface"/>
</ScrollView>
<Button Text="Print"
TextColor="White"
FontFamily="PoppinsSemiBold"
FontSize="17"
WidthRequest="170"
HorizontalOptions="CenterAndExpand"
CornerRadius="5"
x:Name="Prntbutton"
Command="{Binding PrintCommand}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
VoucherPreview_Page.xaml.cs
using BluetoothTest.ViewModel;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace BluetoothTest.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class VoucherPreview_Page : ContentPage
{
public string selectedDevice;
MainViewModel _viewModel = new MainViewModel();
public VoucherPreview_Page()
{
InitializeComponent();
BindingContext = _viewModel;
MyDevices.ItemsSource = _viewModel.pairedDevices;
}
void MyDevicePicker_SelectedIndexChanged(object sender, System.EventArgs e)
{
selectedDevice = ((Picker)sender).SelectedItem as string;
Preferences.Set("SelectedDevice", selectedDevice);
}
private void canvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintGLSurfaceEventArgs e)
{
var imgbyte = _viewModel.GenerateVoucher(sender, e);
}
}
}
I want to be able to print the image that appears in the voucher preview
Upvotes: 0
Views: 19