Results 1 to 14 of 14
Like Tree1Likes
  • 1 Post By StoneBrooks

Thread: Need help with POS printer

  1. #1
    bkirt is offline Member
    Join Date
    May 2007
    Posts
    5
    Rep Power
    0

    Default Need help with POS printer

    I have a 100% Java POS application. The receipt printer is installed as the default Windows XP printer but on a USB port. I am using the Java Printable interface to print receipts. I insert the needed text, etc into a JLabel and print it. This all works fine. My problem is opening the cash drawer which is attached to the printer. I must send a 0x07 (ASCII BEL character) to the printer which then opens the drawer. For some reason the bel never gets sent.

    Is the JLabel removing it? I know it is possible to send it through a Windows printer as there is a test provided with the printer and it works. I have also tried sending the 07 directly to the printer as a Java byte. I have tried opening both the Windows printer name and the USB port as files but that also does not work.

    If anyone has an answer, I will forever be in your debt.

    Thanks in advance,
    Bayless

  2. #2
    levent Guest

    Default

    Hi Bayless,

    Welcome to Java Forums!

    I have also tried sending the 07 directly to the printer as a Java byte.
    Did this work?

    Can you also paste your test program with JLabel here? (Please put your program inside code tag to make it more readable.)

  3. #3
    bkirt is offline Member
    Join Date
    May 2007
    Posts
    5
    Rep Power
    0

    Default POS printer test

    Hi Levent,

    Here is the test program followed by my ReceiptPrinter class. From the current symptoms, I am beginning to suspect that my problem is not knowing how to address the USB port that the printer is attached to. Windows does let me send characters directly to LPT1 (one of the test cases in the following) but I cannot seem to do the same to either of my USB printers.

    Thanks very much for your help.

    Bayless

    Java Code:
    /*
     * PrintTest.java
     *
     * Created on April 24, 2007, 12:19 PM
     */
    
    package com.sailok.util;
    
    import java.awt.Dimension;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    
    public class PrintTest extends javax.swing.JFrame {
        private ReceiptPrinter receiptPrinter = new ReceiptPrinter();
        private FileOutputStream fos;
        
        public PrintTest() {
            initComponents();
            setPreferredSize(new Dimension(300, 200));
            pack();
            try {
        /*
         * Note: only one of the following should be used at any time
         * although both should be attempted separately
         * attempt to open printer by its Windows printer name
         */
    //            fos = new FileOutputStream("Star TSP100 Cutter (TSP143)");
        // attempt to open printer by its USB port name
                fos = new FileOutputStream("USB002");
        // attempt to open LPT1 as a test of procedures only
    //            fos = new FileOutputStream("LPT1");
            }
            catch (FileNotFoundException e) {
               JOptionPane.showMessageDialog(this, "Cannot open file\n" + e.getMessage(),
                       "Warning", JOptionPane.WARNING_MESSAGE);
            }
        }
        
        private void initComponents() {
            openButton = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            display = new javax.swing.JTextArea();
            exitButton = new javax.swing.JButton();
    
            getContentPane().setLayout(null);
    
            setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
            openButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            openButton.setText("Open");
            openButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    openButtonActionPerformed(evt);
                }
            });
    
            getContentPane().add(openButton);
            openButton.setBounds(151, 120, 80, 23);
    
            display.setColumns(20);
            display.setRows(5);
            jScrollPane1.setViewportView(display);
    
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(10, 10, 220, 92);
    
            exitButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            exitButton.setText("Exit");
            exitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    exitButtonActionPerformed(evt);
                }
            });
    
            getContentPane().add(exitButton);
            exitButton.setBounds(10, 120, 70, 23);
    
            pack();
        }
    
        private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
            try {
                fos.close();
            }
            catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Unable to close printer port",
                        "Warning", JOptionPane.WARNING_MESSAGE);
            }
            dispose();
        }
    
        private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // this section attempts to send the BEL character to the printer port
            byte bel = 0x07;
            try {
                fos.write(bel);
                fos.flush();
            }
            catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Error trying to write\n" + e.getMessage(),
                        "Warning", JOptionPane.WARNING_MESSAGE);
            }
        // this section appends the BEL to  the printed message and sends it to the Windows printer
            String msg = "test";
            msg += ((char) 0x07);
            receiptPrinter.printIt(msg);
        // this section displays a hex dump of the printed message
        // note that the BEL is being converted to a box and that
        // is what actually prints on the printer instead of the beep
            for (int i = 0; i < msg.length(); i += 5) {
                for (int j = 0; j < 5; j++) {
                    if ((i + j) < msg.length()) {
                        int x = msg.charAt(i + j);
                        display.append(String.format("&#37;02x ", x));
                    }
                }
                display.append("   ");
                for (int j = 0; j < 5; j++) {
                    if (i + j < msg.length()) {
                        char c = msg.charAt(i + j);
                        display.append(String.format(" %c", c));
                    }
                }
                display.append("\n");
            }
        }
        
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PrintTest().setVisible(true);
                }
            });
        }
        
        private javax.swing.JTextArea display;
        private javax.swing.JButton exitButton;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JButton openButton;
        
    }
    
    
    /**
     * com.sailok.util.ReceiptPrinter.java
     * <p>
     * This class provides a means to print a text or graphics message to 
     * a receipt printer. It includes an option to pop up a JOptionPane 
     * with a configurable message that will cause the program to wait for 
     * the print to finish before continuing. It is fully copyrighted and 
     * owned by the developer, SailOK Software, Oklahoma City, OK.
     * <p>
     * A license to use, executed by SailOK, is required to use the program 
     * in any way. A source code license is also available. If you have a
     * source code license then you may modify the program in any way you
     * desire. Any such modifications, however, will not be covered under 
     * any SailOK warranty. The program may not be resold, even if you 
     * have made modifications to it.
     * <p>
     * Any other use of this program or any of its parts is unauthorized
     * and is punishable by law.
     * <p>
     * Created on May 2, 2007, 11:58 AM
     */
    
    package com.sailok.util;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import java.awt.print.PrinterJob;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.Color;
    import java.awt.Graphics;
    
    /**
     * This class provides a means to print a text or graphics message to 
     * a receipt printer. It includes an option to pop up a JOptionPane 
     * with a configurable message that will cause the program to wait for 
     * the print to finish before continuing. 
     * <p>
     * @author Bayless Kirtley
     */
    public class ReceiptPrinter implements Printable {
        private JFrame printFrame;
        private String waitMsg;
    
    /** Inner class for the actual printed object */
        class PrintFrame extends JFrame {
            PrintFrame(String msg) {
                setBackground(new Color(255, 255, 255, 0));        
                add(new JLabel(msg));
                pack();
                setVisible(true);
            }
        }
    
        /** Creates a new instance of ReceiptPrinter with a default wait message */
        public ReceiptPrinter() {
            waitMsg = "Wait for the printer to finish\nClick the OK button when done";
        }
        
        /**
         * Creates a new instance of ReceiptPrinter with a wait message.
         *
         * @param   msg     the wait message
         */
        public ReceiptPrinter(String msg) {
            waitMsg = msg;
        }
    
        /** 
         * Sends the actual message to the receipt printer - does not wait.
         *
         * @param   msg     the actual message to be printed
         */
        public void printIt(String msg) {
            printIt(msg, false);
        }
        
        /** 
         * Sends the actual message to the receipt printer.
         *
         * @param   msg     the actual message to be printed
         * @param   wait    show JOptionPane to wait for print to finish
         */
        public void printIt(String msg, boolean wait) {
            printFrame = new PrintFrame(msg);
            PrinterJob job = PrinterJob.getPrinterJob();
            PageFormat format = job.defaultPage();
            format.setOrientation(PageFormat.PORTRAIT);
            job.setPrintable(this, format);
            try {
                job.print();
                if (wait)
                    JOptionPane.showMessageDialog(null, waitMsg, "Information", 
                            JOptionPane.INFORMATION_MESSAGE);
            } catch (PrinterException e) {
                e.printStackTrace();
            }
            printFrame.dispose();
        }
    
        /**
         * Print method required by Printable interface.
         *
         * @param   g       the graphics context
         * @param   format  the page format
         * @param   pagenum the page number requested to print
         * @return  int     flag indicating page existance
         */
        public int print(Graphics g, PageFormat format, int pagenum) {
            if (pagenum > 0) return Printable.NO_SUCH_PAGE;
            g.translate((int) format.getImageableX(),
                    (int) format.getImageableY());
            printFrame.paint(g);
            return Printable.PAGE_EXISTS;
        }
    }
    Last edited by levent; 05-14-2007 at 09:51 PM. Reason: You seem to forget closing your [code] tag :)

  4. #4
    levent Guest

    Default

    Bayless,

    As far as i see, you try to open the printer as a file using the paths USB002, LPT1.. These should not work!

    You might try to access USB port with a Java USB API.

  5. #5
    bkirt is offline Member
    Join Date
    May 2007
    Posts
    5
    Rep Power
    0

    Default

    Levent,

    Opening LPT1 does work but, unfortunately, my printer is on a USB port which, as you say, does not work. Thanks for the advice. I checked out the JavaUSB and it is not only very complex for what I need but it also does not support Windows yet, Linux only.

    I think I have done enough experimenting now to be convinced that the Java paint methods all convert the non-displayable characters into something else, a small empty box, it looks like. After sending the test yesterday, I modified another sample program that prints the contents of a file and bypasses any screen display. With that, I still get the same result. It does use the drawString method to display characters. Isn't there some way I can pass a non-displayable character through the Printable interface? That just seems like such a basic and simple thing, I can't imagine that it is not possible.

    Bayless

  6. #6
    levent Guest

    Default

    I see. I guess you will not be able to do that without a lower level API.

    By the way, this Java USB API looks like working on windows. You may try it.

  7. #7
    bkirt is offline Member
    Join Date
    May 2007
    Posts
    5
    Rep Power
    0

    Default

    Thank you again. I found that link earlier from your previous suggestion. It sounds like it could work although somewhat complicated. I will study it and probably implement in the future.

    Meanwhile I found an easier, although not ideal, solution. After considerable study of the printer vendor's very sketchy documentation, I found that they provide a virtual serial port emulation to support legacy applications. With a minimum of rework, I was able to implement that and it does get the job done. The major drawback seems to be that the virtual port disable the standard printer driver. The result appears as a full second delay between opening the drawer and printing the receipt. This happens regardless of the order of the operations. I can live with that for now until I get installed and running. Later I will look into the USB solution.

    Thanks again for all your help,
    Bayless

  8. #8
    Award is offline Member
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default 100% POS Application

    Hi bKirt,

    I've been trying to develop a POS application for my upcoming business for the past 5 months. The POS printer I bought is still not cooperating.

    I tried your code but its not working. I keep an error as 'Status' on the printer (Mecer Posiflex PP5200 Partial Cut v3L) properties.

    The printer prints a test page and is out of the box. Can you please advise? What printer are you using? I tried reading the manual but its not giving me much. Is there any settings I need to perform on the printer?

    Award.

  9. #9
    bkirt is offline Member
    Join Date
    May 2007
    Posts
    5
    Rep Power
    0

    Default

    My printer is a tar TSP100. After getting the crutch to work, I have not revisited the problem and probably will not as that small delay has not caused concern.

    What I finally ended up with was sending the receipt the the standard Java Printable facility. It appears to convert non-printable characters to something printable so the 0x07 was not being received by the printer to open the cash drawer.

    As pointed out in the thread above, there are packages that provide a Java interface to the USB ports. The complexity was just too much to deal with for such a small function. The printer manufacturer also provided a serial port emulator along with the standard USB driver. After installing that, I was able to send the non-printable 0x07 to the printer through this emulator as if it were on COM3. The disadvantage was a one second delay between the two transmissions, regardless of the order of sending. By dinking aound with my application, I was able to make that pause unnoticeable. I believe I send the 0x07 first, followed by the receipt.

  10. #10
    Award is offline Member
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default Receipt printer

    /**
    * Sends the actual message to the receipt printer.
    *
    * @param msg the actual message to be printed
    * @param wait show JOptionPane to wait for print to finish
    */
    public void printIt(String msg, boolean wait) {
    printFrame = new PrintFrame(msg);
    PrinterJob job = PrinterJob.getPrinterJob();
    PageFormat format = job.defaultPage();
    format.setOrientation(PageFormat.PORTRAIT);
    job.setPrintable(this, format);
    try {
    job.print();
    if (wait)
    JOptionPane.showMessageDialog(null, waitMsg, "Information",
    JOptionPane.INFORMATION_MESSAGE);
    } catch (PrinterException e) {
    e.printStackTrace();
    }
    printFrame.dispose();
    }


    O.K. This code works now but; the 'msg' (text message) is not printed in full. I break up the 'msg' as multiple lines and only half of the first line is printed. It doesn't even print a single full sentence.

    Is there another way to directly work with printer margins from this code? I've applied different margin settings in the printer properties and this doesn't work.

  11. #11
    webomatic is offline Member
    Join Date
    Jul 2009
    Posts
    1
    Rep Power
    0

    Default

    Hello everyone!

    I am really glad to have finally joined this community!

    I really do need your help guys :( it's a matter of career actually. if I don't get this assignment done I pretty much will fail the class.

    I have tried searching and doing tests but with no success about sending the info to the printer that after it prints it CUTS the paper (the printer has a cutter) and also to be able to print in RED color (the printer also has a red ribbon as well as black)

    can someone PLEASE help me out?

    On another note....I was able to print to ONE printer at the time...but is there a way to send the msg to be printed on multiple printers at once or even if it's not at same time I just want to be able to send the msg along with the cutting and color code to multiple printers on the network

    Thanks in advance and I will be forever grateful to whomever can help me or point me in the right direction.

  12. #12
    ramadread is offline Member
    Join Date
    Jul 2009
    Posts
    8
    Rep Power
    0

    Default

    wow .. Interesting

  13. #13
    StoneBrooks is offline Member
    Join Date
    Aug 2010
    Posts
    1
    Rep Power
    0

    Lightbulb How about this?

    Java Code:
    package isHuge;
    
    import javax.print.PrintService;
    import java.awt.print.PrinterJob;
    import javax.print.DocPrintJob;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.SimpleDoc;
    
    public class OpenCashDrawer {
    
        PrinterJob printerJob;
    
        public OpenCashDrawer() {
            PrintService tsp100 = getPrintService("Star TSP100 Cutter (TSP143)");
            try {
                DocPrintJob job = tsp100.createPrintJob();
                String openDrawerCommand = ((char) 0x07) + "";
                byte by[] = openDrawerCommand.getBytes();
                DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
                Doc doc = new SimpleDoc(by, flavor, null);
                job.print(doc, null);
            } catch (Exception e) {
                System.out.println("Whoa bro. The printer is balls. Check it:");
                e.printStackTrace();
            }
        }
    
        private PrintService getPrintService(String serviceName) {
            PrintService[] ps = PrinterJob.lookupPrintServices();
            for (int i = 0; i < ps.length; i++) {
                if (ps[i].getName().indexOf(serviceName) >= 0) {
                    return ps[i];
                }
            }
            System.out.println("Aw SNAP! I like, can't find a printer with "
                    + serviceName + " in the name dude.");
            System.exit(1);
            return null;
        }
    
        public static void main(String[] args) {
            OpenCashDrawer ocd = new OpenCashDrawer();
        }
    }
    chacal likes this.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Help with dox matrix printer
    By Albert in forum Advanced Java
    Replies: 7
    Last Post: 09-06-2011, 09:50 AM
  2. Sending text to printer
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 05-25-2009, 07:14 AM
  3. Specifying a Network Printer in Printer Servlet
    By shapez in forum New To Java
    Replies: 0
    Last Post: 03-06-2008, 04:21 PM
  4. Replies: 0
    Last Post: 08-09-2007, 07:30 AM
  5. ElegantJ Printer Bean 1.1
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 07-06-2007, 04:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •