Print to a Network Printer Using Ip Address

I want to send in a filename and a printer's IP address to specify which printer to print to.

I am getting an error saying "Settings to access printer 'xxx.xxx.xxx.xxx' are not valid." when I get to printdoc.Print().

How to I set which printer to print to based on the IP Address?

printdoc = new PrintDocument();
printdoc.PrinterSettings.PrinterName = IPAddress.Trim;
printdoc.DocumentName = FileName;
printdoc.Print();

How to solve this issue? It's a C# vs2010 standalone Windows application.

2

5 Answers

here is the complete working code of IP printer (Model GK420t ZPL And you can access any IP printer). Just replace only three things 1) Add you IP address 2) add your port number 3) Add you PNG File path

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Printing;
using System.Net.NetworkInformation;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Printing;





namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {     
            string ipAddress = "Your IP address";
            int port = Your port number;

            string zplImageData = string.Empty;
            string filePath = @"your png file path";
            byte[] binaryData = System.IO.File.ReadAllBytes(filePath);
            foreach (Byte b in binaryData)
            {
                string hexRep = String.Format("{0:X}", b);
                if (hexRep.Length == 1)
                    hexRep = "0" + hexRep;
                zplImageData += hexRep;
            }
            string zplToSend = "^XA" + "^FO50" + "50^GFA,120000,120000,100" + binaryData.Length + ",," + zplImageData + "^XZ";
            string printImage = "^XA^FO115,50^IME:LOGO.PNG^FS^XZ";

            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(ipAddress, port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream(), Encoding.UTF8);
                writer.Write(zplToSend);
                writer.Flush();
                writer.Write(printImage);
                writer.Flush();
                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                // Catch Exception
            }


    }
        }

    }

I was finally able to get this going

VB: dim

Imports System.IO
Imports System.Net, System.Net.Sockets
.
.
.
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
  Try
    Dim IPAddress As String = txtIPAddr.Text 'ie: 10.0.0.91;
    Dim port As Integer = txtPort.Text 'ie: 9100

    Dim client As System.Net.Sockets.TcpClient = New System.Net.Sockets.TcpClient()
    client.Connect(IPAddress, port)
    Dim reader As StreamReader = New StreamReader(txtFilename.Text) 'ie: C:\\Apps\\test.txt
    Dim writer As StreamWriter = New StreamWriter(client.GetStream())
    Dim testFile As String = reader.ReadToEnd()
    reader.Close()
    writer.Write(testFile)
    writer.WriteLine("Hello World!")
    writer.Flush()
    writer.Close()
    client.Close()
  Catch ex As Exception
    MessageBox.Show("Error: " + ex.Message)
  End Try
End Sub

C#:

using System.IO;
using System.Net;
using System.Net.Sockets;
.
.
.
private void btnPrint_Click(object sender, EventArgs e) {
  try {
    string ipAddress = txtIPAddr.Text.ToString(); ; //ie: 10.0.0.91
    int port = int.Parse(txtPort.Text.ToString()); //ie: 9100

    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
    client.Connect(ipAddress, port);
    StreamReader reader = new StreamReader(txtFilename.Text.ToString()); //ie: C:\\Apps\\test.txt
    StreamWriter writer = new StreamWriter(client.GetStream());
    string testFile = reader.ReadToEnd();
    reader.Close();
    writer.Write(testFile);
    writer.WriteLine("Hello World!");
    writer.Flush();
    writer.Close();
    client.Close();
  }
  catch (Exception ex) {
    MessageBox.Show(ex.Message, "Error");
  }
}

Is your printer accessible in network for the machine you're running your software on?

As you can see, you should call IsValid to determine if everything is ok and you can also use InstalledPrinters property to get a list of printers installed on the system. I guess you don't have installed the printer correctly or you don't have sufficient permissions or something like that.

edit: if using name works, this should do the trick: How to access a printer name from IP on network in C#?

3

You can't do using IPAddress. The printer has to be already installed on your Machine.

On some systems, that function is reserved for administrators only so you're app should not be creating printers. After all, you don't have the drivers for every printer type either.

Your app can only get the name of a printer to use that is already installed. You cannot use just the IP address.

2
public IActionResult PrintAPI(OrderItemGet model)
    {
        SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);
        // Create a 'SocketPermission' object for two ip addresses.
        SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
        SecurityElement securityElement1 = socketPermission2.ToXml();
        // 'SocketPermission' object for 'Connect' permission
        SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
        // Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
        // for 'All' ports for the ip-address.
        SecurityElement securityElement4 = new SecurityElement("URI", "192.168.100.200");
        //securityElement2.AddChild(securityElement3);
        securityElement2.AddChild(securityElement4);
        securityElement1.AddChild(securityElement2);
        // Obtain a 'SocketPermission' object using 'FromXml' method.
        socketPermission2.FromXml(securityElement1);
        // Obtain a 'SocketPermission' object using 'FromXml' method.
        socketPermission2.FromXml(securityElement1);
        Socket clientSock = new Socket(
            AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp
            );
        //clientSock.NoDelay = true;
        IPAddress ip = IPAddress.Parse("192.168.100.200");
        IPEndPoint remoteEP = new IPEndPoint(ip, 4730);
        clientSock.Connect(remoteEP);
        if (!clientSock.Connected)
        {
            return BadRequest("Printer is not connected");
        }
        Encoding enc = Encoding.ASCII;
        string GS = Convert.ToString((char)29);
        string ESC = Convert.ToString((char)27);
        string COMMAND = "";
        COMMAND = ESC + "@";
        COMMAND += GS + "V" + (char)1;
        //byte[] bse = 
        char[] bse = COMMAND.ToCharArray();
        byte[] paperCut = enc.GetBytes(bse);
        // Line feed hexadecimal values
        byte[] bEsc = new byte[4];
        // Sends an ESC/POS command to the printer to cut the paper
        string t = ("                  " + model.PrintTitle.ToUpper() + "\r\n");
        t = t + ("----------------------------------------\r\n");
        t = t + ("Table:  Table-C           BillNo: 120 \r\n");
        t = t + ("----------------------------------------\r\n");
        t = t + ("Date :2022/01/21  Order: Sylvia \r\n");
        t = t + ("=======================================\r\n");
        t = t + ("\r\n");
        t = t + (" SN. 1   Item: MoMo         Qty: 2   \r\n");
        t = t + ("\r\n");
        t = t + ("\r\n");
        t = t + ("\r\n");
        t = t + ("\r\n");
        t = t + ("\r\n");
        t = t + ("\r\n");
        char[] array = t.ToCharArray();
        byte[] byData = enc.GetBytes(array);
        clientSock.Send(byData);
        clientSock.Send(paperCut);
        //clientSock.DuplicateAndClose(2);
        clientSock.Close();
        return Ok(200);   
    }

For more details click here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest