当前位置: 首页 > 知识库问答 >
问题:

在java中使用热敏打印机打印接收器

澹台浩广
2023-03-14

我必须使用Java通过热敏打印机打印收据。我已经完成了所有工作。我的程序从数据库中获取数据,并使用特殊字符、制表符和\n转换为一个字符串。然后将字符串传递给另一个将其转换为图形的方法。

问题是当我点击打印按钮时,白纸就出来了。我注意到我的字符串的前4-5个字符被打印在纸币最末端右上角的最后一行。我的打印机是爱普生TM-T81。

  public void printThisBill()
  {

      DefaultTableModel mod = (DefaultTableModel) jTable1.getModel();
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
      DateFormat timeFormat = new SimpleDateFormat("HH:mm");
      //get current date time with Date()
      Date date = new Date();
      Date time = new Date();
      String Date = dateFormat.format(date);
      String Time = timeFormat.format(time);
      String Header = 
            "   ****Super Market****       \n"
            + "Date: "+Date+"     Time: "+Time+"\n"
            + "---------------------------------\n"
            + "Name          Qty    Rate     Amt\n"
            + "---------------------------------\n";

      String amt  =    
            "\n \n \nTotal Amount = "+  amt()   +"\n"
            + "Tax ="   +  tax()    + "\n"
            + "*********************************\n"
            + "Thank you. \n";

      String bill = Header;
      int i = 0;
      do
      {

         String name =     ""+ mod.getValueAt(i, 2);
         String qty =      ""+ mod.getValueAt(i, 3);
         String rate =     ""+ mod.getValueAt(i, 4);
         String amount =   ""+ mod.getValueAt(i, 6);

         if(name.length() > 12)
         {
             name = name.substring(0, 12)+"  ";
         }
         else
         {
             for(int j= name.length()-12; j<= name.length(); j++);
             {
                 name = name+" ";
             } 
         }


         if(qty.length()<=5)
         {
             for(int j= 0; j<= qty.length()-5; j++);
             {
                qty = qty+" ";
             }
         }

         rate = rate;
         String items = 
             name+"\t"+qty+"\t"+rate+"\t"+amount+"\n";

         bill = bill+ items;       
         i++;

     } while(i <= mod.getRowCount()-1);

     bill = bill+amt;
     System.out.println(bill);
     printCard(bill);
     dispose();
 }

打印账单的方法是:

public static void printCard(final String bill )
{
       Printable contentToPrint = new Printable(){
       @Override
        public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException 
        {
           if (page > 0) {
                return NO_SUCH_PAGE;
            }
            pageFormat.setOrientation(PageFormat.LANDSCAPE);
            Graphics2D g2d = (Graphics2D)graphics.create();

            g2d.setPaint(Color.black);
            g2d.setFont(new Font("Arial", Font.BOLD, 10));
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableX());



            g2d.drawString(bill, 0, 0);

            return PAGE_EXISTS;
         }
       };

       PrinterJob job = PrinterJob.getPrinterJob();
       job.setPrintable(contentToPrint);
       //You can show a print dialog before printing by job by wrapping the following blocks with a conditional statement if(job.printDialog()){...}
       try 
       {
           job.print();
       } catch (PrinterException e) 
       {
           System.err.println(e.getMessage());
       }

 }

问题是什么?我该如何解决?我认为我没有在drawString()方法中设置正确的参数。

还是别的什么?任何帮助我都将不胜感激。!

共有2个答案

呼延聪
2023-03-14

嗯,我认为你应该使用ESC/POS命令来打印,阅读Epson TM-T81的打印机技术手册。我在TM-U220D上也遇到了类似的问题,我为此编写了一个类。这可能没有帮助,因为打印机是不同的,无论如何,我附上它作为参考:

//------------------------
//-- PrinterOptions.java
//------------------------

public class PrinterOptions {
    String commandSet = "";

    public String initialize() {
        final byte[] Init = {27, 64};
        commandSet += new String(Init);
        return new String(Init);
    }

    public String chooseFont(int Options) {
        String s = "";
        final byte[] ChooseFontA = {27, 77, 0};
        final byte[] ChooseFontB = {27, 77, 1};
        final byte[] ChooseFontC = {27, 77, 48};
        final byte[] ChooseFontD = {27, 77, 49};

        switch(Options) {
            case 1:
            s = new String(ChooseFontA);
            break;

            case 2:
            s = new String(ChooseFontB);
            break;

            case 3:
            s = new String(ChooseFontC);
            break;

            case 4:
            s = new String(ChooseFontD);
            break;

            default:
            s = new String(ChooseFontB);
        }
        commandSet += s;
        return new String(s);
    }

    public String feedBack(byte lines) {
        final byte[] Feed = {27,101,lines};
        String s = new String(Feed);
        commandSet += s;
        return s;
    }

    public String feed(byte lines) {
        final byte[] Feed = {27,100,lines};
        String s = new String(Feed);
        commandSet += s;
        return s;
    }

    public String alignLeft() {
        final byte[] AlignLeft = {27, 97,48};
        String s = new String(AlignLeft);
        commandSet += s;
        return s;
    }

    public String alignCenter() {
        final byte[] AlignCenter = {27, 97,49};
        String s = new String(AlignCenter);
        commandSet += s;
        return s;
    }

    public String alignRight() {
        final byte[] AlignRight = {27, 97,50};
        String s = new String(AlignRight);
        commandSet += s;
        return s;
    }

    public String newLine() {
        final  byte[] LF = {10};
        String s = new String(LF);
        commandSet += s;
        return s;
   }

   public String reverseColorMode(boolean enabled) {
        final byte[] ReverseModeColorOn = {29, 66, 1};
        final byte[] ReverseModeColorOff = {29, 66, 0};

        String s = "";
        if(enabled)
            s = new String(ReverseModeColorOn);
        else
            s = new String(ReverseModeColorOff);

        commandSet += s;
        return s;
    } 

    public String doubleStrik(boolean enabled) {
        final byte[] DoubleStrikeModeOn = {27, 71, 1};
        final byte[] DoubleStrikeModeOff = {27, 71, 0};

        String s="";
        if(enabled)
            s = new String(DoubleStrikeModeOn);
        else
            s = new String(DoubleStrikeModeOff);

        commandSet += s;
        return s;
    } 

    public String doubleHeight(boolean enabled) {
        final byte[] DoubleHeight = {27, 33, 17};
        final byte[] UnDoubleHeight={27, 33, 0};

        String s = "";
        if(enabled)
            s = new String(DoubleHeight);
        else
            s = new String(UnDoubleHeight);

        commandSet += s;
        return s;
    }

    public String emphasized(boolean enabled) {
        final byte[] EmphasizedOff={27 ,0};
        final byte[] EmphasizedOn={27 ,1};

        String s="";
        if(enabled)
            s = new String(EmphasizedOn);
        else
            s = new String(EmphasizedOff);

        commandSet += s;
        return s;
    } 

    public String underLine(int Options) {
        final byte[] UnderLine2Dot = {27, 45, 50};
        final byte[] UnderLine1Dot = {27, 45, 49};
        final byte[] NoUnderLine = {27, 45, 48};

        String s = "";
        switch(Options) {
            case 0:
            s = new String(NoUnderLine);
            break;

            case 1:
            s = new String(UnderLine1Dot);
            break;

            default:
            s = new String(UnderLine2Dot);
        }
        commandSet += s;
        return new String(s);
    }

    public String color(int Options) {
        final byte[] ColorRed = {27, 114, 49};
        final byte[] ColorBlack = {27, 114, 48};

        String s = "";
        switch(Options) {
            case 0:
            s = new String(ColorBlack);
            break;

            case 1:
            s = new String(ColorRed);
            break;

            default:
            s = new String(ColorBlack);
        }
        commandSet += s;
        return s;
    }

    public String finit() {
        final byte[] FeedAndCut = {29, 'V', 66, 0};

        String s = new String(FeedAndCut);

        final byte[] DrawerKick={27,70,0,60,120};   
        s += new String(DrawerKick);

        commandSet+=s;
        return s;
    }

    public String addLineSeperator() {
        String lineSpace = "----------------------------------------";
        commandSet += lineSpace;
        return lineSpace;
    }

    public void resetAll() {
        commandSet = "";
    }

    public void setText(String s) {
        commandSet+=s;
    }

    public String finalCommandSet() {
        return commandSet;
    }
}

feed Printer()--方法

private static boolean feedPrinter(byte[] b) {
    try {       
        AttributeSet attrSet = new HashPrintServiceAttributeSet(new PrinterName("EPSON TM-U220 ReceiptE4", null)); //EPSON TM-U220 ReceiptE4

        DocPrintJob job = PrintServiceLookup.lookupPrintServices(null, attrSet)[0].createPrintJob();       
        //PrintServiceLookup.lookupDefaultPrintService().createPrintJob();  

        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(b, flavor, null);
        PrintJobWatcher pjDone = new PrintJobWatcher(job);

        job.print(doc, null);
        pjDone.waitForDone();
        System.out.println("Done !");
    } catch (javax.print.PrintException pex) {
        System.out.println("Printer Error " + pex.getMessage());
        return false;
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

现在准备账单:)

PrinterOptions p=new PrinterOptions();

p.resetAll();
p.initialize();
p.feedBack((byte)2);
p.color(0);
p.alignCenter();
p.setText("The Dum Dum Name");
p.newLine();
p.setText("Restaurant Dining");
p.newLine();
p.addLineSeperator();
p.setText("Bling Bling");
p.newLine();
p.addLineSeperator();
p.newLine();

p.alignLeft();
p.setText("POD No \t: 2001 \tTable \t: E511");
p.newLine();              

p.setText("Res Date \t: " +  "01/01/1801 22:59");

p.newLine();
p.setText("Session \t: Evening Session");
p.newLine();
p.setText("Staff \t: Bum Dale");
p.newLine();
p.addLineSeperator();
p.newLine();
p.alignCenter();
p.setText(" - Some Items - ");
p.newLine();
p.alignLeft();
p.addLineSeperator();

p.newLine();

p.setText("No \tItem\t\tUnit\tQty");
p.newLine();
p.addLineSeperator();
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");
p.setText("1" + "\t" + "Aliens Everywhere" + "\t" +  "Rats" + "\t" + "500");

p.addLineSeperator();
p.feed((byte)3);
p.finit();

feedPrinter(p.finalCommandSet().getBytes());
朱高丽
2023-03-14

我发现:

Java Pos热敏打印机示例

这对我很管用。不需要外部库。

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

public class PrinterService implements Printable {

    public List<String> getPrinters(){

        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printServices[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);

        List<String> printerList = new ArrayList<String>();
        for(PrintService printerService: printServices){
            printerList.add( printerService.getName());
        }

        return printerList;
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page)
            throws PrinterException {
        if (page > 0) { /* We have only one page, and 'page' is zero-based */
            return NO_SUCH_PAGE;
        }

        /*
         * User (0,0) is typically outside the imageable area, so we must
         * translate by the X and Y values in the PageFormat to avoid clipping
         */
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        /* Now we perform our rendering */

        g.setFont(new Font("Roman", 0, 8));
        g.drawString("Hello world !", 0, 10);

        return PAGE_EXISTS;
    }

    public void printString(String printerName, String text) {

        // find the printService of name printerName
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printService[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);
        PrintService service = findPrintService(printerName, printService);

        DocPrintJob job = service.createPrintJob();

        try {

            byte[] bytes;

            // important for umlaut chars
            bytes = text.getBytes("CP437");

            Doc doc = new SimpleDoc(bytes, flavor, null);


            job.print(doc, null);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void printBytes(String printerName, byte[] bytes) {

        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printService[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);
        PrintService service = findPrintService(printerName, printService);

        DocPrintJob job = service.createPrintJob();

        try {

            Doc doc = new SimpleDoc(bytes, flavor, null);

            job.print(doc, null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PrintService findPrintService(String printerName,
            PrintService[] services) {
        for (PrintService service : services) {
            if (service.getName().equalsIgnoreCase(printerName)) {
                return service;
            }
        }

        return null;
    }
}

主要课程是:

public class Main {

    public static void main(String[] args) {

        PrinterService printerService = new PrinterService();

        System.out.println(printerService.getPrinters());

        //print some stuff. Change the printer name to your thermal printer name.
        printerService.printString("EPSON-TM-T20II", "\n\n testing testing 1 2 3eeeee \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        // cut that paper!
        byte[] cutP = new byte[] { 0x1d, 'V', 1 };

        printerService.printBytes("EPSON-TM-T20II", cutP);

    }

}
 类似资料:
  • 我有一台爱普生热敏打印机,现在我要打印一些足够长的收据,我使用爱普生提供的代码样本。代码如下所示,现在的问题是,当收据超过一定长度(约30cm)时,打印机会停止并剪切收据,如下图所示。我如何打印长收据没有自动剪切。

  • 我必须用热敏打印机打印发票收据。我用Zjiang热敏打印机打印收据。他们还提供了手册和演示项目。在演示项目中,他们使用一个库“btsdk.jar”来实现连接和打印。 我已经成功地建立了打印机和android设备之间的连接。但是没有关于文本对齐(中心、左、右)&单元格宽度、高度的指导原则。 我试过了。它只通过改变format2变量来改变文本高度。 打印信息- 发票收据

  • 问题内容: 我正在为具有内置行式打印机的Android设备开发应用程序。我必须与此打印机进行交互,并使用它来打印收据上的详细信息,然后使用裁纸器自动剪切该收据。我已经在其中看到了一些ESC命令,但是我不知道如何执行这些ESC命令。 关于Casio设备打印机,我有三个主要问题: 1.我已经使用了内置打印机的打印代码,但是打印后切纸刀没有激活 2.我不知道如何在android中将ESC命令发送到打印机

  • 编辑:所以在一天的混乱之后。我的问题是spintf。我最初认为我的循环是错误的。

  • 早在2007年,我就用Java编写了一些软件来控制Epson TM90收据打印机。我的软件使用JavaPOS API。 这个JavaPOS软件似乎已经不存在了! 2012年,从Win7通过USB从用Wava编写的应用程序驱动Epson Receipt打印机的正确方法是什么? TIA BfW

  • 有没有办法让我在蓝牙热敏打印机上打印收据,因为我真的很难在Flutter上找到解决方案?任何事情都能帮上忙,我真的很感谢你的回答