Click here to Skip to main content
15,881,600 members
Articles / Programming Languages / Visual Basic
Article

How The Raw Data is Printed

Rate me:
Please Sign up or sign in to vote.
2.00/5 (4 votes)
4 Feb 2005 107.6K   5.1K   18   17
This article explains how raw data is printed

Sample Image - Print_Raw_Data.jpg

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.

VB.NET
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.


VB.NET
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 (<a href="mailto:garconalapipe@hotmail.com"><U>garconalapipe@hotmail.com</U></a>) 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

VB.NET
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

Reference

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot working for me Pin
Bhavik_Patel16-Jul-14 19:28
professionalBhavik_Patel16-Jul-14 19:28 
QuestionHow to read info from printer? Pin
leandronf2-Aug-13 6:46
leandronf2-Aug-13 6:46 
QuestionThis code not working on Terminal Server Pin
Member 87640697-Feb-13 7:11
Member 87640697-Feb-13 7:11 
Questionhow to i receive or capture raw data from printjob Pin
kamonwanjang12-Sep-12 16:14
kamonwanjang12-Sep-12 16:14 
QuestionNot working in USB printer Pin
dhiraj thakur9-Sep-12 21:13
dhiraj thakur9-Sep-12 21:13 
QuestionÇıktı alamadım Pin
alpilim18-Apr-12 4:40
alpilim18-Apr-12 4:40 
GeneralMy vote of 5 Pin
ingenvzla20-Feb-12 11:58
ingenvzla20-Feb-12 11:58 
Questionquestion from Jim Peters Pin
Sean Ewington22-Oct-07 5:41
staffSean Ewington22-Oct-07 5:41 
GeneralError occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
ratnesh00722-Jun-06 0:32
ratnesh00722-Jun-06 0:32 
GeneralRe: Error occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
Duncan Edwards Jones22-Jun-06 1:44
professionalDuncan Edwards Jones22-Jun-06 1:44 
GeneralRe: Error occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
healeysa1-Aug-06 13:38
healeysa1-Aug-06 13:38 
GeneralDoes Not Work in Win98SE Pin
JaimeVSDC24-May-05 6:16
JaimeVSDC24-May-05 6:16 
GeneralRe: Does Not Work in Win98SE Pin
teloglu12-Dec-05 2:52
teloglu12-Dec-05 2:52 
GeneralRe: Does Not Work in Win98SE Pin
Duncan Edwards Jones22-Jun-06 1:47
professionalDuncan Edwards Jones22-Jun-06 1:47 
QuestionRe: Does Not Work in Win98SE Pin
Nikola Kratka17-Jun-07 23:14
Nikola Kratka17-Jun-07 23:14 
AnswerRe: Does Not Work in Win98SE Pin
Duncan Edwards Jones18-Jun-07 7:40
professionalDuncan Edwards Jones18-Jun-07 7:40 
GeneralRe: Does Not Work in Win98SE Pin
Nikola Kratka18-Jun-07 9:41
Nikola Kratka18-Jun-07 9:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.