Saturday 6 August 2016

How to print multiple labels using BinaryPrinterCommands with neodynamic?


public void ClientPrintForMultipleFiles(string printerName, string filesInfo, bool isLabel)
{
    //fileInfo is collection of FileName and FilePath details
    if (!String.IsNullOrEmpty(printerName))
    {

        //Below code is required when you called this function from jquery ajax call
        //filesInfo = filesInfo.Replace("FileName:", "FileName\":\"").Replace(",FilePath:", "\",\"FilePath\":\"").Replace("{", "{\"").Replace("}", "\"}");

        List<FileData> fileDetails = JsonConvert.DeserializeObject<List<FileData>>(filesInfo);

        if (!isLabel)
        {
            ClientPrintJob cpj = new ClientPrintJob();
            foreach (var obj in fileDetails)
            {
                cpj.PrintFileGroup.Add(new PrintFile(obj.FilePath, obj.FileName));
            }
            cpj.ClientPrinter = new InstalledPrinter(System.Web.HttpUtility.UrlDecode(printerName));
            cpj.SendToClient(System.Web.HttpContext.Current.Response);
        }
        else if (isLabel)
        {
            ClientPrintJob cpj = new ClientPrintJob();
            List<byte[]> buffer = new List<byte[]>();
            foreach (var obj in fileDetails)
            {
                string filePath = System.IO.Path.Combine(obj.FilePath, obj.FileName);
                buffer.Add(System.IO.File.ReadAllBytes(filePath));
            }
            cpj.BinaryPrinterCommands = JoinArrays(buffer);
            cpj.ClientPrinter = new InstalledPrinter(System.Web.HttpUtility.UrlDecode(printerName));
            cpj.SendToClient(System.Web.HttpContext.Current.Response);
        }
    }
}

private byte[] JoinArrays(IEnumerable<byte[]> arrays)
{
    int offset = 0;
    byte[] fullArray = new byte[arrays.Sum(a => a.Length)];
    foreach (byte[] array in arrays)
    {
        Buffer.BlockCopy(array, 0, fullArray, offset, array.Length);
        offset += array.Length;
    }
    return fullArray;
}
......
......
public class FileData
{
    public string FileName { get; set; }
    public string FilePath { get; set; }
}