2021年9月28日 星期二

EscPOS print image

 參考來源

--

Public Class EscPOS


    Private Shared PrintNam As String = "POS"


    Public Shared Property PrinterName

        Set(value)

            PrintNam = value

        End Set

        Get

            Return PrintNam

        End Get

    End Property


    ' Structure and API declarions:

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _

    Structure DOCINFOW

        <MarshalAs(UnmanagedType.LPWStr)> Public pDocName As String

        <MarshalAs(UnmanagedType.LPWStr)> Public pOutputFile As String

        <MarshalAs(UnmanagedType.LPWStr)> Public pDataType As String

    End Structure


    <DllImport("winspool.Drv", EntryPoint:="OpenPrinterW", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter As IntPtr, ByVal pd As Long) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="ClosePrinter", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="StartDocPrinterW", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal level As Int32, ByRef pDI As DOCINFOW) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Boolean

    End Function

    <DllImport("winspool.Drv", EntryPoint:="WritePrinter", _

       SetLastError:=True, CharSet:=CharSet.Unicode, _

       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _

    Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal pBytes As IntPtr, ByVal dwCount As Int32, ByRef dwWritten As Int32) As Boolean

    End Function


    Public Shared Function PrintImage(BM As Bitmap) As Boolean


        Dim b As Byte() = ConvertImagetoBytes(BM)

        Dim bSuccess As Boolean

        Dim pUnmanagedBytes As IntPtr


        ' Allocate some unmanaged memory for those bytes.

        pUnmanagedBytes = Marshal.AllocCoTaskMem(b.Count)

        ' Copy the managed byte array into the unmanaged array.

        Marshal.Copy(b, 0, pUnmanagedBytes, b.Count)

        ' Send the unmanaged bytes to the printer.

        bSuccess = EscPOS.PrintBytes(b)


        Return bSuccess

    End Function

    Public Shared Function PrintBytes(Document As Byte()) As Boolean

        Dim hPrinter As IntPtr      ' The printer handle.

        Dim dwError As Int32        ' Last error - in case there was trouble.

        Dim di As DOCINFOW       ' Describes your document (name, port, data type).

        Dim dwWritten As Int32      ' The number of bytes written by WritePrinter().

        Dim bSuccess As Boolean     ' Your success code.


        ' Set up the DOCINFO structure.


        di = New DOCINFOW

        di.pDocName = "RAW LOGO"

        di.pDataType = "RAW"


        hPrinter = New IntPtr(0)


        bSuccess = False

        If OpenPrinter(PrinterName.Normalize(), hPrinter, 0) Then

            If StartDocPrinter(hPrinter, 1, di) Then

                Dim managedData As Byte()

                Dim unmanagedData As IntPtr


                managedData = Document

                unmanagedData = Marshal.AllocCoTaskMem(managedData.Length)

                Marshal.Copy(managedData, 0, unmanagedData, managedData.Length)


                If StartPagePrinter(hPrinter) Then

                    bSuccess = WritePrinter(hPrinter, unmanagedData, managedData.Length, dwWritten)

                    EndPagePrinter(hPrinter)

                End If

                Marshal.FreeCoTaskMem(unmanagedData)

                EndDocPrinter(hPrinter)

            End If

            ClosePrinter(hPrinter)

        End If

        If bSuccess = False Then

            dwError = Marshal.GetLastWin32Error()

        End If

        Return bSuccess

    End Function

    Public Shared Function ConvertImagetoBytes(BM As Bitmap) As Byte()

        Dim Data As BitMapData = GetBitmapData(BM)

        Dim Op As New MemoryStream

        Dim bw As New BinaryWriter(Op)


        bw.Write(Chr(Keys.Escape))

        bw.Write("@"c)


        ' So we have our bitmap data sitting in a bit array called "dots."

        ' This is one long array of 1s (black) and 0s (white) pixels arranged

        ' as if we had scanned the bitmap from top to bottom, left to right.

        ' The printer wants to see these arranged in bytes stacked three high.

        ' So, essentially, we need to read 24 bits for x = 0, generate those

        ' bytes, and send them to the printer, then keep increasing x. If our

        ' image is more than 24 dots high, we have to send a second bit image

        ' command to draw the next slice of 24 dots in the image.


        ' Set the line spacing to 24 dots, the height of each "stripe" of the

        ' image that we're drawing. If we don't do this, and we need to

        ' draw the bitmap in multiple passes, then we'll end up with some

        ' whitespace between slices of the image since the default line

        ' height--how much the printer moves on a newline--is 30 dots.

        bw.Write(Chr(Keys.Escape))

        bw.Write("3"c)

        ' '3' just means 'change line height command'

        bw.Write(CByte(24))


        ' OK. So, starting from x = 0, read 24 bits down and send that data

        ' to the printer. The offset variable keeps track of our global 'y'

        ' position in the image. For example, if we were drawing a bitmap

        ' that is 48 pixels high, then this while loop will execute twice,

        ' once for each pass of 24 dots. On the first pass, the offset is

        ' 0, and on the second pass, the offset is 24. We keep making

        ' these 24-dot stripes until we've run past the height of the

        ' bitmap.

        Dim offset As Integer = 0

        Dim width As Byte()


        While offset < Data.Height

            ' The third and fourth parameters to the bit image command are

            ' 'nL' and 'nH'. The 'L' and the 'H' refer to 'low' and 'high', respectively.

            ' All 'n' really is is the width of the image that we're about to draw.

            ' Since the width can be greater than 255 dots, the parameter has to

            ' be split across two bytes, which is why the documentation says the

            ' width is 'nL' + ('nH' * 256).

            bw.Write(Chr(Keys.Escape))

            bw.Write("*"c)

            ' bit-image mode

            bw.Write(CByte(33))

            ' 24-dot double-density

            width = BitConverter.GetBytes(Data.Width)

            bw.Write(width(0))

            ' width low byte

            bw.Write(width(1))

            ' width high byte

            For x As Integer = 0 To Data.Width - 1

                ' Remember, 24 dots = 24 bits = 3 bytes.

                ' The 'k' variable keeps track of which of those

                ' three bytes that we're currently scribbling into.

                For k As Integer = 0 To 2

                    Dim slice As Byte = 0

                    ' A byte is 8 bits. The 'b' variable keeps track

                    ' of which bit in the byte we're recording.

                    For b As Integer = 0 To 7

                        ' Calculate the y position that we're currently

                        ' trying to draw. We take our offset, divide it

                        ' by 8 so we're talking about the y offset in

                        ' terms of bytes, add our current 'k' byte

                        ' offset to that, multiple by 8 to get it in terms

                        ' of bits again, and add our bit offset to it.

                        Dim y As Integer = (((offset \ 8) + k) * 8) + b

                        ' Calculate the location of the pixel we want in the bit array.

                        ' It'll be at (y * width) + x.

                        Dim i As Integer = (y * Data.Width) + x

                        ' If the image (or this stripe of the image)

                        ' is shorter than 24 dots, pad with zero.

                        Dim v As Boolean = False

                        If i < Data.Dots.Length Then

                            v = Data.Dots(i)

                        End If

                        ' Finally, store our bit in the byte that we're currently

                        ' scribbling to. Our current 'b' is actually the exact

                        ' opposite of where we want it to be in the byte, so

                        ' subtract it from 7, shift our bit into place in a temp

                        ' byte, and OR it with the target byte to get it into there.

                        slice = slice Or CByte((If(v, 1, 0)) << (7 - b))

                    Next

                    ' Phew! Write the damn byte to the buffer

                    bw.Write(slice)

                Next

            Next

            ' We're done with this 24-dot high pass. Render a newline

            ' to bump the print head down to the next line

            ' and keep on trucking.

            offset = offset + 24

            bw.Write(vbCrLf.ToCharArray)

        End While


        ' Restore the line spacing to the default of 30 dots.

        bw.Write(Chr(Keys.Escape))

        bw.Write("3"c)

        bw.Write(CByte(30))


        bw.Flush()


        Return Op.ToArray

    End Function

    Private Shared Function GetBitmapData(BM As Bitmap) As BitMapData

        Dim threshold = 127

        Dim index As Integer = 0

        Dim dimensions As Integer = BM.Width * BM.Height

        Dim dots As BitArray = New BitArray(dimensions)

        Dim res As New BitMapData

        Dim a As Integer


        For y = 0 To BM.Height - 1

            For x = 0 To BM.Width - 1

                Dim col As Color = BM.GetPixel(x, y)

                Dim luminance = CInt(col.R * 0.3 + col.G * 0.59 + col.B * 0.11)

                If (luminance < threshold) = True Then

                    a = 1

                End If

                dots(index) = (luminance < threshold)

                index = index + 1

            Next

        Next

        res.Dots = dots : res.Height = BM.Height : res.Width = BM.Width

        Return res

    End Function

    Private Class BitMapData

        Public Dots As BitArray

        Public Height As Int16

        Public Width As Int16

    End Class


    ' When the function is given a printer name and an unmanaged array of  

    ' bytes, the function sends those bytes to the print queue.

    ' Returns True on success or False on failure.

    Private Shared Function PrintEsto(ByVal pBytes As IntPtr, ByVal dwCount As Int32) As Boolean

        Dim hPrinter As IntPtr      ' The printer handle.

        Dim dwError As Int32        ' Last error - in case there was trouble.

        Dim di As DOCINFOW = Nothing         ' Describes your document (name, port, data type).

        Dim dwWritten As Int32      ' The number of bytes written by WritePrinter().

        Dim bSuccess As Boolean     ' Your success code.


        ' Set up the DOCINFO structure.

        With di

            .pDocName = "RAW Document"

            .pDataType = "RAW"

        End With

        ' Assume failure unless you specifically succeed.

        bSuccess = False

        If OpenPrinter(PrinterName, hPrinter, 0) Then

            If StartDocPrinter(hPrinter, 1, di) Then

                If StartPagePrinter(hPrinter) Then

                    ' Write your printer-specific bytes to the printer.

                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)

                    EndPagePrinter(hPrinter)

                End If

                EndDocPrinter(hPrinter)

            End If

            ClosePrinter(hPrinter)

        End If

        ' If you did not succeed, GetLastError may give more information

        ' about why not.

        If bSuccess = False Then

            dwError = Marshal.GetLastWin32Error()

        End If

        Return bSuccess

    End Function


    ' SendFileToPrinter()

    ' When the function is given a file name and a printer name, 

    ' the function reads the contents of the file and sends the

    ' contents to the printer.

    ' Presumes that the file contains printer-ready data.

    ' Shows how to use the SendBytesToPrinter function.

    ' Returns True on success or False on failure.

    Public Shared Function PrintFile(ByVal szFileName As String) As Boolean

        ' Open the file.

        Try

            Dim fs As New FileStream(szFileName, FileMode.Open)

            ' Create a BinaryReader on the file.

            Dim br As New BinaryReader(fs)

            ' Dim an array of bytes large enough to hold the file's contents.

            Dim bytes(fs.Length) As Byte

            Dim bSuccess As Boolean

            ' Your unmanaged pointer.

            Dim pUnmanagedBytes As IntPtr


            ' Read the contents of the file into the array.

            bytes = br.ReadBytes(fs.Length)

            ' Allocate some unmanaged memory for those bytes.

            pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)

            ' Copy the managed byte array into the unmanaged array.

            Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)

            ' Send the unmanaged bytes to the printer.

            bSuccess = PrintEsto(pUnmanagedBytes, fs.Length)

            ' Free the unmanaged memory that you allocated earlier.

            Marshal.FreeCoTaskMem(pUnmanagedBytes)

            fs.Close()

            Return bSuccess

        Catch ex As Exception

            MsgBox(ex.Message)

            Return False

        End Try

    End Function


    ' When the function is given a string and a printer name,

    ' the function sends the string to the printer as raw bytes.

    Public Shared Function PrintString(ByVal szString As String)

        Dim pBytes As IntPtr

        Dim dwCount As Int32

        Dim Res As Boolean

        ' How many characters are in the string?

        dwCount = szString.Length()

        ' Assume that the printer is expecting ANSI text, and then convert

        ' the string to ANSI text.

        pBytes = Marshal.StringToCoTaskMemAnsi(szString)

        ' Send the converted ANSI string to the printer.

        Res = PrintEsto(pBytes, dwCount)

        Marshal.FreeCoTaskMem(pBytes)

        Return Res

    End Function


End Class




使用方法:

If EsImpresionTermica Then

            If File.Exists(My.Application.Info.DirectoryPath & "\Settings.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}\Logo.conf") Then _

                RawPrinting.EscPOS.PrintBytes(File.ReadAllBytes(My.Application.Info.DirectoryPath & "\Settings.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}\Logo.conf"))

        Else

            Dim MSe As New MemoryStream

            Dim BWe As New BinaryWriter(MSe)

            BWe.Write(Chr(&H1B))

            BWe.Write("@"c) 'Inicia Imresora

            BWe.Write(Chr(&H1B))

            BWe.Write(CByte(3))

            BWe.Write(Chr(18)) 'Establece interlineado

            BWe.Write(Chr(&H1B))

            BWe.Write("U"c)

            BWe.Write(Chr(1)) 'Impresión unidireccional

            BWe.Write(Chr(&H1B))

            BWe.Write("a"c)

            BWe.Write(Chr(1)) 'Centra Impresión

            BWe.Write(Chr(&H1B))

            BWe.Write(vbCrLf.ToCharArray)

            BWe.Write(Encoding.ASCII.GetBytes(Encabezado))

            BWe.Write(Chr(10))

            BWe.Write(Chr(10))

            BWe.Flush()

            BWe.Close()

            RawPrinting.EscPOS.PrintBytes(MSe.ToArray)

        End If

    End Sub


ESC/POS: Print QR Code on Receipt

 ESC/POS: Print QR Code on Receipt

on Thursday, September 13, 2018


QR code has been used widely in the past few years; either for ticketing, purchasing and etc. Since last year, it's usage become trending technology when e-wallet industry emerge. Some of us might have different ways on how to print it on receipt/ticket; send qr code as image and print, or send the data to be convert to qr code and let the printer do the work. This entry will guide you on how to print qr code using receipt printer (Model: Pioneer STEP-5e Receipt Printer) by using ESC/POS command in C#/.NET.


COMMON ESC/POS COMMANDS

ESC a 0 = align left

ESC a 1 = align center

ESC a 2 = align right

ESC E 1 = turn on bold/emphasize mode

ESC E 0 = turn off bold/emphasize mode

ESC d n = feed/extra nth line

GS V 66 = partial cut for receipt

ESC @ = initialize printer


QRCODE ESC/POS COMMANDS

1. Selects QR Code model

Function 165: GS ( k pL pH cn fn n1 n2


2. Sets the module size of QR Code

Function 167: GS ( k pL pH cn fn n


3. Selects the error correction level for QR Code

Function 169: GS ( k pL pH cn fn n


4. Stores symbol data in the symbol storage area

Function 180: GS ( k pL pH cn fn m d1,d2...dk


5. Prints QR Code symbol data stored in the system saving region

Function 181: GS ( k pL pH cn fn m


Let's get into the coding part. Hooray! Please note that different receipt printer might use different ESC/POS command as some might use custom ESC/POS commands; such as Star TSP100 Cutter (TSP143). Please refer to the receipt printer manual accordingly. :D


//Convert ASCII/Decimal

string ESC = Convert.ToString((char)27);

string GS = Convert.ToString((char)29);

string center = ESC + "a" + (char)1; //align center

string left = ESC + "a" + (char)0; //align left

string bold_on = ESC + "E" + (char)1; //turn on bold mode

string bold_off = ESC + "E" + (char)0; //turn off bold mode

string cut = ESC + "d" + (char)1 + GS + "V" + (char)66; //add 1 extra line before partial cut

string initp = ESC + (char)64; //initialize printer

string buffer = ""; //store all the data that want to be printed

string QrData = "LianaAliBlogspotMy"; //data to be print in QR code

//Print Text

buffer += center;

buffer += "This text is align center!\n"; //to enter or add newline: \n

buffer += left;

buffer += "This text is align left!\n"; //align left is already set as default if not specified

//Print QRCode

Encoding m_encoding = Encoding.GetEncoding("iso-8859-1"); //set encoding for QRCode

int store_len = (QrData).Length + 3;

byte store_pL = (byte)(store_len % 256);

byte store_pH = (byte)(store_len / 256);

buffer += initp; //initialize printer

buffer += m_encoding.GetString(new byte[] { 29, 40, 107, 4, 0, 49, 65, 50, 0 });

buffer += m_encoding.GetString(new byte[] { 29, 40, 107, 3, 0, 49, 67, 8 });

buffer += m_encoding.GetString(new byte[] { 29, 40, 107, 3, 0, 49, 69, 48 });

buffer += m_encoding.GetString(new byte[] { 29, 40, 107, store_pL, store_pH, 49, 80, 48 });

buffer += QrData;

buffer += m_encoding.GetString(new byte[] { 29, 40, 107, 3, 0, 49, 81, 48 });

//Cut Receipt

buffer += cut + initp;

//Send to Printer

RawPrinterHelper.SendStringToPrinter(ConfigurationManager.AppSettings["STEP-5e"], buffer);


EscPos class

 參考來源

--

Public Class EscPos


'if you want to use decimal values in your methods.

Public Function intTobyte(data As Integer()) As Byte()


Dim byteData As Byte() = data.[Select](Function(x) CType(x, Byte)).ToArray()

' coonvert int array to byte

Return byteData

End Function


'initialize printer

'ESC @

Public Sub initializePrinter(szPrinterName As String)


Dim command As Integer() = {27, 64}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(command))

End Sub



'print text


Public Function printText(szPrinterName As String, data As String) As Boolean

'for more character sets: http://www.ascii-codes.com/


'for another charsets: 

'Encoding ascii = Encoding.GetEncoding("ascii");

'Encoding windows = Encoding.GetEncoding("Windows-1252");


'you must use this encoding  for  brazilian portuguese special characters: ^,~,ç,á...

Dim brazilian As Encoding = Encoding.GetEncoding("IBM860")

Dim byteData As Byte() = brazilian.GetBytes(data)


RawPrinterHelper.SendBytesToPrinter(szPrinterName, byteData)





Return True

End Function


' Print Position Commands

'ESC a n

Public Function SelectJustification(szPrinterName As String, justification_code As Integer) As Boolean


'0= default 

'48 left

'1,49 centering

'2,50 right


Dim align As Integer() = {27, 97, justification_code}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(align))


Return True

End Function






'Character Control Commands


'use this mode to cancel another mode.

Public Function normalModeText(szPrinterName As String) As Boolean

Dim normal As Integer() = {27, 33, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(normal))


Return True

End Function


'Character font A (12 × 24) selected.

Public Function charFontAText(szPrinterName As String) As Boolean


Dim fontA As Integer() = {27, 33, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(fontA))



Return True

End Function


'Character font B (9 × 17) selected.

Public Function charFontBText(szPrinterName As String) As Boolean

Dim fontB As Integer() = {27, 33, 1}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(fontB))



Return True


End Function


'Emphasized mode is turned on

Public Function emphasizedModeText(szPrinterName As String) As Boolean

Dim mode As Integer() = {27, 33, 8}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(mode))

Return True

End Function


'Double-height selected.

Public Function doubleHeightText(szPrinterName As String) As Boolean

Dim height As Integer() = {27, 33, 16}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(height))


Return True

End Function

'Double-width selected.

Public Function DoubleWidthText(szPrinterName As String) As Boolean

Dim width As Integer() = {27, 33, 32}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(width))

Return True

End Function



'Underline mode is turned on

Public Function UnderlineModeText(szPrinterName As String) As Boolean

Dim underline As Integer() = {27, 33, 128}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(underline))

Return True

End Function



'print and Line feed

Public Function lineFeed(szPrinterName As String, numLines As Integer) As Boolean

' fucntion LF 

Dim lf As Integer() = {10}

Dim i As Integer = 1

While i <= numLines

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(lf))

i += 1

End While

Return True

End Function


'Generate pulse in Real Time

Public Function drawerKick(szPrinterName As String) As Boolean

' function DLE DC4 fn m t (fn=1)



Dim pulse As Integer() = {27, 112, 0, 100, 200}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(pulse))



Return True

End Function


'execute test print

Public Function testPrint(szPrinterName As String) As Boolean

'function GS ( A pL pH n m


Dim test As Integer() = {29, 40, 65, 2, 0, 0, _

2}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(test))


Return True

End Function



'Select an international character set

Public Function charSet(szPrinterName As String, language As Integer) As Boolean

'function ESC R n

'0-USA

'12-Latin America

'

Dim char_set As Integer() = {27, 82, language}


RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(char_set))


Return True



End Function



'select character code table

Public Function codeTable(szPrinterName As String, language As Integer) As Boolean

'function Esc t n

' 0 - PC437 (USA: Standard Europe)]

' 40 [ISO8859-15 (Latin9)]

' 3 [PC860 (Portuguese)]


Dim code As Integer() = {27, 116, language}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(code))



Return True

End Function


'Select cut mode and cut paper

Public Function CutPaper(szPrinterName As String) As Boolean

'hex 1D 56 m, m =0,1,48,49


Dim cut As Integer() = {29, 86, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(cut))


Return True

End Function



'activate printer buzzer

Public Function buzzer(szPrinterName As String) As Boolean




'hex data = "1b 28 41 05 00 61 64 03 0a 0a";

Dim buzzer As Integer() = {27, 40, 65, 5, 0, 97, _

100, 3, 10, 10}


RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(buzzer))

' RawPrinterHelper.SendASCiiToPrinter(szPrinterName, data);

Return True


End Function


'*************************** barcode  commands **********************************


'GS h n - sets bar the height of bar code to n dots.

Public Function barcode_height(szPrinterName As String, Optional range As Integer = 162) As Boolean

' default = 162


'range 1 ≤ n ≤ 255

Dim height As Integer() = {29, 104, range}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(height))

Return True

End Function


' GS w n Set bar code width

Public Function barcode_width(szPrinterName As String, Optional range As Integer = 3) As Boolean

'range = 2 ≤ n ≤ 6

Dim width As Integer() = {29, 119, range}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(width))

Return True

End Function


'GS f n Select a font for the HRI characters when printing a bar code.

Public Function barcodeHRI_chars(szPrinterName As String, Optional font_code As Integer = 0) As Boolean

'default 0 

'[Range] n = 0, 1, 48, 49

Dim hri As Integer() = {29, 102, font_code}



RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(hri))

Return True

End Function



'GS H n Select print position of HRI characters

Public Function barcodeHRIPostion(szPrinterName As String, Optional position_code As Integer = 1) As Boolean

'default = 0

'[Range] 0 ≤ n ≤ 3, 48 ≤ n ≤ 51 


Dim print_position As Integer() = {29, 72, position_code}


RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(print_position))

Return True



End Function


'GS k Print barcode

'<Function A>

Public Function printBarcode(szPrinterName As String, data As String, Optional type As Integer = 2) As Boolean

'for this example 2 = JAN/EAN13

Dim barcode As Integer() = {29, 107, type}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(barcode))


RawPrinterHelper.SendStringToPrinter(szPrinterName, data)

Dim nul As Integer() = {0}

' null char at the end.

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(nul))

Return True

End Function


'GS k Print Barcode

' <Function B>

Public Function printBarcodeB(szPrinterName As String, data As String, Optional type As Integer = 73) As Boolean

'for this example 73 = CODE128

Dim size As Integer = CType(data.Length, Integer)

'  the number of bytes of bar code data

Dim barcode As Integer() = {29, 107, type, size}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(barcode))

RawPrinterHelper.SendStringToPrinter(szPrinterName, data)



Return True

End Function


'*************************** barcode  commands **********************************




'function to print Qrcode

Public Function printQrcode(Strdata As String, szPrinterName As String) As Boolean






Dim length As Integer = Strdata.Length + 3

'  string size  + 3

'int length = Strdata.Length; 

Dim length_low_byte As Byte = 0, length_high_byte As Byte = 0

length_low_byte = CType((length And &Hff), Byte)

'low byte used in function 180 

length_high_byte = CType(((length >> 8) And &Hff), Byte)

'high byte in function 180 


'if you don't want to use shift operator:

'int length_low_byte = length % 256;

'int length_high_byte = length / 256;



initializePrinter(szPrinterName)


'<Function ESC a n> Select justification  

Dim escAn As Integer() = {27, 97, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(escAn))




'<Function GS L> Set left margin

Dim fGsl As Integer() = {29, 76, 0, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(fGsl))


'<Function 165> GS ( k p L p H cn fn n (cn = 49,fn = 65)  QR Code: Select the model

Dim f165 As Integer() = {29, 40, 107, 4, 0, 49, _

65, 50, 0}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(f165))



'<Function 167> GS ( k pL pH cn fn n (cn = 49, fn = 67) QR Code: Set the size of module

Dim f167 As Integer() = {29, 40, 107, 3, 0, 49, _

67, 4}

'  size of qrcode:  1-16

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(f167))




'<Function 169> GS ( k pL pH cn fn n (cn = 49, fn = 69) QR Code: Select the error correction level

Dim f169 As Integer() = {29, 40, 107, 3, 0, 49, _

69, 48}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(f169))



'<Function 180> GS ( k pL pH cn fn m d1…dk (cn = 49, fn = 80) QR Code: Store the data in the symbol storage area

'pL and pH are the low- and high-order bytes of a 16-bit integer value that specifies the length in bytes of the following data  


Dim f180 As Integer() = {29, 40, 107, length_low_byte, length_high_byte, 49, _

80, 48}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(f180))




'send string/url to printer

'RawPrinterHelper.SendASCiiToPrinter(szPrinterName, Strdata);

RawPrinterHelper.SendStringToPrinter(szPrinterName, Strdata)


'<Function 181> GS ( k pL pH cn fn m (cn = 49, fn = 81) QR Code: Print the symbol data in the symbol storage area

Dim f181 As Integer() = {29, 40, 107, 3, 0, 49, _

81, 48}

RawPrinterHelper.SendBytesToPrinter(szPrinterName, intTobyte(f181))


'



Return True

End Function


End Class

ESC-POS-USB-NET

 https://www.nuget.org/packages/ESC-POS-USB-NET/

2021年9月24日 星期五

宙斯國際貿易有限公司ERP系統

 承接宙斯國際貿易有限公司ERP系統維護


9月中已簽下該公司的ERP系統維護

只是原開發公司真的是有意或無意

既然簽定的合約是要給原始程式碼

卻在開方案,發生很多form錯誤;無法正常開啟

另主要架構 menu 控制及權限,控制包在dll內

這樣要我怎維護啊...Orz

只能請窗口加把勁,再請對方協助到可以維護和加功能

我才有辦法接手維護


提這部分出來,是要告知大家

當您們正使用的系統的原開發商已不熱情或失連了

歡迎您們來找我,有原始碼可以依維護;若沒有程式碼,可以思考打掉重練的準備


紅櫻花食品整合系統

20211019 更新:

又是虛晃,那就等真正簽約;再說了.....Orz!!

真的須要有非常耐度,老是想要又退卻止步


****************

 202109 挑戰-紅櫻花食品整合系統

1.POS系統[電子發票] (多門市架構)

2.STOCK系統 (多門市/總部系統/外部訂單系統)

3.BOM (工廠加工/派單/排程/再製加工系統)


2021年H2/Q4 總算還是到了簽約時刻

談了許久,真的一個公司要整合大系統;沒法全包式一次到位

紅櫻花食品老闆,總算還是接受我的建議;先就這三大系統完成後

再來就其他區塊系統整合進來,我真的沒法一次到位;太大了

就這三大系統整合,先完成吧


未來進行開發過程中,將會不定時的分享一些開發的新技術或構想及畫面


歡迎,各行各業想要整併公司系統的;可以來找我




2021年9月23日 星期四

vbnet Json edit

 Imports Newtonsoft.Json

Imports System.IO


Public Class Profile

    Public name As String

    Public gameDir As String

    Public lastVersionId As String

    Public javaArgs As String

    Public launcherVisibilityOnGameClose As String

End Class


Public Class JSON_Object

    Public profiles As Dictionary(Of String, Profile) '' Object -> Dictionary

    Public selectedProfile As String

    Public clientToken As String

    Public authenticationDatabase As Object

    Public selectedUser As String

    Public launcherVersion As Object

End Class


Module Module1


    Sub Main()

        Dim sJsonObj As JSON_Object =

            JsonConvert.DeserializeObject(Of JSON_Object)(File.ReadAllText("C:\example.json"))


        ' Add a new profile.

        sJsonObj.profiles.Add("Test Profile", New Profile With {

                              .name = "Test Profile",

                              .gameDir = "C:\Test",

                              .lastVersionId = "Test"

                          })


        ' Serialize to JSON string.

        Dim settings As New JsonSerializerSettings

        settings.NullValueHandling = NullValueHandling.Ignore

        settings.Formatting = Formatting.Indented

        Dim strJson As String = JsonConvert.SerializeObject(sJsonObj, settings)


        ' Write to file.

        File.WriteAllText("C:\your\writable\path\exampleNew.json", strJson)

    End Sub


End Module

C# to Json 和 Json to C# 線上轉換

 JSON to C# 網站 http://json2csharp.com/

C# to JSON 網站 http://csharp2json.azurewebsites.net/

2021年9月17日 星期五

Image to SQL Server DataBase 應用和寫法記錄

 Load images into a DataGridView

https://gist.github.com/RedSkeeter/b9214f052200556e491526b20debec83


關於在DataGridView中嵌入圖片

https://www.itread01.com/p/623955.html


IMAGE VS VARBINARY(MAX)

https://sqltutorialtips.blogspot.com/2016/11/image-vs-varbinarymax.html

 SqlDbType.Image

https://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database  


SqlDbType.Binary

http://www.aspphp.online/bianchen/VisualBasic/vbzh/201701/117876.html  


VB.NET - How To Save Image Into SQL Server DataBase Using Visual Basic .Net

https://1bestcsharp.blogspot.com/2016/09/vb.net-insert-image-into-sql-database.html


How to Save and Retrieve Image from SQL Server Database on VB.Net

http://tutlogger.blogspot.com/2015/07/how-to-save-and-retrieve-image-from-sql.html

-------------------------------------------------------------


Uploading and retrieving of photos from SQL Database on vb.net windows form

https://social.msdn.microsoft.com/Forums/en-US/f1ccd971-0b9a-4a0e-846f-64ad9cf0587f/uploading-and-retrieving-of-photos-from-sql-database-on-vbnet-windows-form?forum=vbgeneral


2021年9月6日 星期一

License for package Android SDK Build-Tools 30.0.2 not accepted

 vs 2019 的 Xamarin  模擬 Android 真的還是沒改善 CPU 一直是100%

只好放棄了

以前安裝 Android Studio 就沒這些問題,一直忙windows 開發,也沒時間使用Android IDE開發

改變的速度真的太快了!

現就遇到開範本就 License for package Android SDK Build-Tools 30.0.2 not accepted

到底是啥問題阿

查了一下網路其他解法,都什麼指令的,也不行阿

底下,照版本打勾後並下載即可正常運作執行了

---





 







2021年9月5日 星期日

Windows 10 Hyper-V 使用教學

 請參考來源:Hyper-V教學|Windows 10 上的免費虛擬機器 Hyper-V 使用教學


幫忙採收芭樂

 哥哥的芭樂豐產,趁假日有回去農;幫忙採收

真的超級好吃的,外面水果攤賣的等級差不多在1斤50~60元的價位

結果,我媽在鄉下的市場才賣1斤20~25;也差太多了





苦茶苗地植

 趁現都是白天太陽午後有雨的天氣,來地植了

只是有點生氣,網路一些賣茶苗的沒信用.不老實;當初說好是買涔溪軟枝3號

卻混了一大堆雜種均不耐旱,今年旱到7月才開始有雨

真的損失慘重阿,人生真的沒幾個"再等3年"

出貨還一大堆根系斷的,根都不齊;沒那個貨量,至少也要給我都是涔溪軟枝3號阿

現在想來就有氣,真的是浪費我時間.金錢.生命

進400棵,結果都雜種就佔了1/3以上;都不耐旱

等我以後壯大了,能榨油.苗種出貨;我一定不會這樣如此卑劣行為,為了小小錢把自己的招牌信用打臭了

---

底下是大果苦茶苗和一棵超傳統台灣原生的正港茶樹(大葉.小果;下次再拍出來亮相)