Sending raw data to a printer

An awesome printer helper class for sending raw data to a printer. I have found this very useful for sending control codes to our Datamax label printers at work for barcode printing etc.

I added an additional method to the helper class (bodged together from the existing ones!) that accepts a memory stream instead of a file or string.

public static bool SendStreamToPrinter(string szPrinterName, MemoryStream ms, string DocName)
    // Open the file.
    //FileStream fs = new FileStream(szFileName, FileMode.Open);
    // Create a BinaryReader on the file.
    BinaryReader br = new BinaryReader(ms);
    // Dim an array of bytes big enough to hold the file's contents.
    Byte[] bytes = new Byte[ms.Length];
    bool bSuccess = false;
    // Your unmanaged pointer.
    IntPtr pUnmanagedBytes = new IntPtr(0);
    int nLength;

    nLength = Convert.ToInt32(ms.Length);
    // Read the contents of the file into the array.
    bytes = br.ReadBytes(nLength);
    // Allocate some unmanaged memory for those bytes.
    pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
    // Copy the managed byte array into the unmanaged array.
    Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
    // Send the unmanaged bytes to the printer.
    bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength, DocName);
    // Free the unmanaged memory that you allocated earlier.
    return bSuccess;

One thought on “Sending raw data to a printer

  1. Hi.. i tried your added command and also added it on the given class file..
    when i tried to call the procedure. it successfully entered the spooled file but nothing is happening at the printer.. at the spooled file the status is at “Printing”.. I am using Datamax allegro II

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s