How The Raw Data is Printed





2.00/5 (4 votes)
Feb 4, 2005

109367

5133
This article explains how raw data is printed
Introduction
This artical explains how raw data is printed with a sample project.
here is Code, Please read Carefully explanations. Also I have other class RawPrinterHelper. i deleted "Windows generated code" so dont copy then paste this code. Download demo project or source code.
Public Class frmRawDataPrintSample
Inherits System.Windows.Forms.Form
Dim xPrinterName As String = ""
Dim xFileName As String = ""
Private Sub btnPrint_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnPrint.Click
If Not txtText.Text.Length = 0 Then
PrintRawData()
End If
End Sub
Public Sub PrintRawData()
Try
Dim _printDialog As New System.Windows.Forms.PrintDialog
_printDialog.PrinterSettings = New System.Drawing.Printing.PrinterSettings
If _printDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
xPrinterName = _printDialog.PrinterSettings.PrinterName
WriteRawDataToTxtFile(chkPaging.Checked)
End If
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Text could not printed.",
"Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Protected Sub WriteRawDataToTxtFile(ByVal Paging As Boolean)
xFileName = "TextReport" & Now.Minute.ToString & Now.Second.ToString &
Now.Millisecond.ToString
Dim xFile As System.IO.File
' first u have to find a unique file name, my algorithm is below.
Dim i As Short = 1
Do While xFile.Exists(Application.StartupPath & "\" & xFileName &
i.ToString & ".txt")
i += 1
Loop
xFileName = Application.StartupPath & "\" & xFileName & i.ToString & ".txt"
'Write text into Text File
Dim xFileWriter As System.IO.StreamWriter
xFileWriter = xFile.CreateText(xFileName)
Dim sPerPageMaxLineCount, sPageCount As Short
sPerPageMaxLineCount = 64 ' change value according to your paper source
If Paging Then
sPageCount = Math.Ceiling(txtText.Lines.Length / sPerPageMaxLineCount)
For i = 1 To sPageCount
WriteIntoTextFile(xFileWriter, (i - 1) * sPerPageMaxLineCount,
i * sPerPageMaxLineCount)
Next
Else
WriteIntoTextFile(xFileWriter, 0, txtText.Lines.GetUpperBound(0))
End If
xFileWriter.Close()
'Print text file from raw printer
Dim _RawPrinterHelper As New RawPrinterHelper
_RawPrinterHelper._DocumentName = "Raw Data Print Sample"
_RawPrinterHelper.SendFileToPrinter(xPrinterName, xFileName)
'relase objects
xFileWriter = Nothing
xFile = Nothing
_RawPrinterHelper = Nothing
GC.Collect()
'delete file u have created
IO.File.Delete(xFileName)
End Sub
Protected Sub WriteIntoTextFile(ByRef xFileWriter As System.IO.StreamWriter,
ByVal FirstIndex As Integer, ByVal LastIndex As Integer)
If LastIndex > txtText.
Lines.GetUpperBound(0) Then LastIndex = txtText.Lines.GetUpperBound(0)
xFileWriter.WriteLine("")
'{0,-100} is about formatting. if u need some help, search on msdn or
'write to me (<U>garconalapipe@hotmail.com</U>) again . Just a remanding,
'0 is variable index, 100 is character count will be printed. if your data
'is shorter than 100, automatically space will be appended to the data;
'if not, there will be no modification.
'If you use negative sign, it means text will aligned to Left,
'if u dont use (-), it means text will aligned to right
xFileWriter.WriteLine("{0,-70}", "RAW DATA PRINT SAMPLE")
xFileWriter.WriteLine("")
xFileWriter.WriteLine("{0,-100}", DrawLine(100, "="))
For i As Integer = FirstIndex To LastIndex
xFileWriter.WriteLine("{0,-100}", ChangeTurkishCharacters(txtText.Lines(i)))
Next
''' if you want to print less line from PerPageMaxLineCount,at all
''' page or just at last page, You may want to add blanks lines to file.
''' So your printer will put out paper untill the cutting part.
'For i As Short = 0 To sPerPageMaxLineCount - sPrintedLineCount
' xFileWriter.WriteLine("")
'Next
xFileWriter.WriteLine("{0,-100}", DrawLine(100, "="))
End Sub
'In some languages u may need character transformation as in Turkish.
'Raw printers just supports English languages. So u have to change your
'languages special characters to English equivalent
Protected Function ChangeTurkishCharacters(
ByVal sTurkishString As String) As String
Dim sEnglishString As String = ""
If Not sTurkishString Is Nothing Then
For i As Short = 0 To sTurkishString.Length - 1
Select Case sTurkishString.Chars(i)
Case "ı" : sEnglishString &= "i"
Case "İ" : sEnglishString &= "I"
Case "ç" : sEnglishString &= "c"
Case "Ç" : sEnglishString &= "C"
Case "ş" : sEnglishString &= "s"
Case "Ş" : sEnglishString &= "S"
Case "ö" : sEnglishString &= "o"
Case "Ö" : sEnglishString &= "O"
Case "ü" : sEnglishString &= "u"
Case "Ü" : sEnglishString &= "U"
Case "ğ" : sEnglishString &= "g"
Case "Ğ" : sEnglishString &= "G"
Case Else : sEnglishString &= sTurkishString.Chars(i)
End Select
Next
End If
Return sEnglishString
End Function
'Semetimes if you need draw line, use this function
Protected Function DrawLine(ByVal length As Short,
ByVal lineCharacter As Char) As String
Dim s As String = ""
For i As Short = 1 To length
s &= lineCharacter
Next
Return s
End Function
End Class
RawPrinterHelper Class
Imports System.IO
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices
Public Class RawPrinterHelper
Shared xDocumentName As String = "XXX"
Public WriteOnly Property _DocumentName() As String
Set(ByVal Value As String)
xDocumentName = Value
End Set
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 SendBytesToPrinter(ByVal szPrinterName As String,
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 ' 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 = xDocumentName
.pDataType = "RAW"
End With
' Assume failure unless you specifically succeed.
bSuccess = False
If OpenPrinter(szPrinterName, 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 ' SendBytesToPrinter()
Public Shared Function SendFileToPrinter(ByVal szPrinterName As String,
ByVal szFileName As String) As Boolean
' Open the file.
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
bytes = br.ReadBytes(fs.Length)
pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)
Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)
' Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, fs.Length)
' Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes)
fs.Close()
fs = Nothing
Return bSuccess
End Function ' SendFileToPrinter()
Public Shared Function SendStringToPrinter(ByVal szPrinterName As String,
ByVal szString As String)
Dim pBytes As IntPtr
Dim dwCount As Int32
dwCount = szString.Length()
pBytes = Marshal.StringToCoTaskMemAnsi(szString)
SendBytesToPrinter(szPrinterName, pBytes, dwCount)
Marshal.FreeCoTaskMem(pBytes)
End Function
End Class