10

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user3541403
  • 247
  • 1
  • 3
  • 18
  • Possibly relevant: https://stackoverflow.com/a/18722872/5858238 – nyconing Jun 17 '19 at 04:16
  • Printing doesn't even mildly work like this. You don't print to an ip address as this is only the "port" you are printing to. You print to an installed instance of a print driver which has an installed instance (or mapping) of a port (might be LPT, USB, TCP).. HOW is the printer supposed to know how to print "FileName"? If you want to print to IP-ADDR, you need to install an instance of that printers driver and setup the port to use IP-ADDR. – Señor CMasMas Apr 24 '20 at 19:13

5 Answers5

3

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
            }


    }
        }

    }

enter image description here

Asad
  • 563
  • 3
  • 16
2

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");
  }
}
user1388706
  • 191
  • 1
  • 6
0

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

http://msdn.microsoft.com/en-us/library/system.drawing.printing.printersettings.printername.aspx

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#?

Community
  • 1
  • 1
walther
  • 13,466
  • 5
  • 41
  • 67
  • If I give printername instead of ipaddress am able to print document,but its not working with ip address.Have no clue why is it so – user3541403 Sep 13 '14 at 12:33
  • the link u have sent works with servername but not with ipaddress – user3541403 Sep 13 '14 at 12:45
  • 1
    is there any updates on this issue? it does not work with ip addresss... I have "files to be printed" at a DB table from another app... those users choose a printer an its ip is stored... no printer name is available... so... How to set the printername since I only have the ip adress? – Fernando Torres May 26 '15 at 19:28
0

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.

Hiren Patel
  • 1,071
  • 11
  • 34
0
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

Sundar
  • 142
  • 1
  • 15