Click here to Skip to main content
13,202,960 members (57,880 online)
Click here to Skip to main content
Add your own
alternative version

Stats

80.9K views
4.4K downloads
18 bookmarked
Posted 4 Feb 2005

How The Raw Data is Printed

, 4 Feb 2005
Rate this:
Please Sign up or sign in to vote.
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.

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 (<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

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

Share

About the Author

Just Greeky Creek
Web Developer
Turkey Turkey
No Biography provided

You may also be interested in...

Pro
Pro

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
memberleandronf2-Aug-13 6:46 
QuestionThis code not working on Terminal Server Pin
Member 87640697-Feb-13 7:11
memberMember 87640697-Feb-13 7:11 
Hi,

The same code is working on local system, remote system on redirected printer but not working on Terminal server redirected printer please help its very urgent. I am using same code in c#
given on below Link http://support.microsoft.com/?kbid=322091[^]
Questionhow to i receive or capture raw data from printjob Pin
kamonwanjang12-Sep-12 16:14
memberkamonwanjang12-Sep-12 16:14 
QuestionNot working in USB printer Pin
dhiraj thakur9-Sep-12 21:13
memberdhiraj thakur9-Sep-12 21:13 
QuestionÇıktı alamadım Pin
alpilim18-Apr-12 4:40
memberalpilim18-Apr-12 4:40 
GeneralMy vote of 5 Pin
ingenvzla20-Feb-12 11:58
memberingenvzla20-Feb-12 11:58 
Questionquestion from Jim Peters Pin
Sean Ewington22-Oct-07 5:41
adminSean Ewington22-Oct-07 5:41 
GeneralError occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
ratnesh00722-Jun-06 0:32
memberratnesh00722-Jun-06 0:32 
GeneralRe: Error occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
Duncan Edwards Jones22-Jun-06 1:44
memberDuncan Edwards Jones22-Jun-06 1:44 
GeneralRe: Error occured at OpenPrinter(szPrinterName, hPrinter, 0) Pin
healeysa1-Aug-06 13:38
memberhealeysa1-Aug-06 13:38 
GeneralDoes Not Work in Win98SE Pin
JaimeVSDC24-May-05 6:16
memberJaimeVSDC24-May-05 6:16 
GeneralRe: Does Not Work in Win98SE Pin
teloglu12-Dec-05 2:52
memberteloglu12-Dec-05 2:52 
GeneralRe: Does Not Work in Win98SE Pin
Duncan Edwards Jones22-Jun-06 1:47
memberDuncan Edwards Jones22-Jun-06 1:47 
QuestionRe: Does Not Work in Win98SE Pin
Nikola Kratka17-Jun-07 23:14
memberNikola Kratka17-Jun-07 23:14 
AnswerRe: Does Not Work in Win98SE Pin
Duncan Edwards Jones18-Jun-07 7:40
memberDuncan Edwards Jones18-Jun-07 7:40 
GeneralRe: Does Not Work in Win98SE Pin
Nikola Kratka18-Jun-07 9:41
memberNikola 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171020.1 | Last Updated 4 Feb 2005
Article Copyright 2005 by Just Greeky Creek
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid