2

请帮助尝试使用此代码在热敏打印机中打印,我的系统托盘中有打印作业,但我的热敏打印机不打印。PrintReceiptUtil 类:

import java.awt.JobAttributes;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;

import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;


public static void doPrintReceipt() throws IOException, PrintException{

    String defaultPrinter = PrintServiceLookup.lookupDefaultPrintService().getName();
    System.out.println("Default printer: " + defaultPrinter);
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    // prints the famous hello world! plus a form feed
    InputStream is = new ByteArrayInputStream("hello world!\f".getBytes("UTF8"));

    PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();

    pras.add(new Copies(1));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc doc = new SimpleDoc(is, flavor, null);
    DocPrintJob job = service.createPrintJob();

    PrintJobWatcher pjw = new PrintJobWatcher(job);
    job.print(doc, pras);
    pjw.waitForDone();
    is.close();
} 
}

PrintJobWatcher 类:为了监控打印作业,我可以“打印完成”,但我的热敏打印机不打印任何东西

import javax.print.DocPrintJob;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public PrintJobWatcher(DocPrintJob job){

    job.addPrintJobListener(new PrintJobAdapter() {
        public void printJobCanceled(PrintJobEvent pje) {
            allDone();
        }
        public void printJobCompleted(PrintJobEvent pje) {
            allDone();
        }
        public void printJobFailed(PrintJobEvent pje) {
            allDone();
        }
        public void printJobNoMoreEvents(PrintJobEvent pje) {
            allDone();
        }
        void allDone() {
            synchronized (PrintJobWatcher.this) {
                done = true;
                System.out.println("Printing done ...");
                PrintJobWatcher.this.notify();
            }
        }
    });
}

public synchronized void waitForDone() {
    try {
        while (!done) {
            wait();
        }
    } catch (InterruptedException e) {
    }
}
}
4

2 回答 2

7

@bhuvanpavan 的工作版本

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.JTextArea;

public class NewClass {

    public void a() {
        PageFormat format = new PageFormat();
        Paper paper = new Paper();

        double paperWidth = 3;//3.25
        double paperHeight = 3.69;//11.69
        double leftMargin = 0.12;
        double rightMargin = 0.10;
        double topMargin = 0;
        double bottomMargin = 0.01;

        paper.setSize(paperWidth * 200, paperHeight * 200);
        paper.setImageableArea(leftMargin * 200, topMargin * 200,
                (paperWidth - leftMargin - rightMargin) * 200,
                (paperHeight - topMargin - bottomMargin) * 200);

        format.setPaper(paper);

        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(OrientationRequested.PORTRAIT);
//testing 

        PrinterJob printerJob = PrinterJob.getPrinterJob();
        Printable printable = new ReceiptPrint();

        format = printerJob.validatePage(format);
        boolean don = printerJob.printDialog();
        printerJob.setPrintable(printable, format);
        try {
            printerJob.print(aset);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class ReceiptPrint implements Printable {

    SimpleDateFormat df = new SimpleDateFormat();
    String receiptDetailLine;
    public static final String pspace = "               ";//15-spaces

    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {

        df.applyPattern("dd/MM/yyyy HH:mm:ss");
        String strText = null;
        final String LF = "\n";// text string to output
        int lineStart;           // start index of line in textarea
        int lineEnd;             // end index of line in textarea
        int lineNumber;
        int lineCount;
        final String SPACE = "          ";//10 spaces
        final String SPACES = "         ";//9
        final String uline = "________________________________________";
        final String dline = "----------------------------------------";
        String greetings = "THANKS FOR YOUR VISIT";
        receiptDetailLine = "asdasdasda";

        Graphics2D g2d = (Graphics2D) graphics;
        Font font = new Font("MONOSPACED", Font.BOLD, 9);

        if (pageIndex < 0 || pageIndex >= 1) {
            return Printable.NO_SUCH_PAGE;
        }
        JTextArea textarea = new JTextArea(10, 40);

 //testing
        textarea.append(SPACES + "sadasdsad" + "\n");

        textarea.append(" " + SPACES + "sadasdsad" + "\n");

        textarea.append(SPACES + "sadasdsad" + "\n");

        textarea.append("" + SPACES + "sadasdsad" + "\n");

        textarea.append(SPACES + "sadasdsad" + "\n");

        textarea.append(uline + "\n");
        textarea.append("Order Ref:" + "   " + receiptDetailLine + "\n");
        textarea.append(dline + "\n");
        textarea.append(" Qty     Description" + SPACES + "  Price" + LF);
        textarea.append(dline + "\n");

        System.out.println(2);

        String printedLine = "       Service Charge Complimentary";
        textarea.append(printedLine + LF);

        textarea.append(LF + SPACES + "   Your Reciept\n" + SPACE + greetings + LF);
        textarea.append(df.format(new Date()) + LF);
        textarea.setEditable(false);

        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        g2d.setFont(font);
        lineNumber = 0;
        lineCount = textarea.getLineCount();
        strText = textarea.getText();
        /*MediaTracker mt = new MediaTracker(textarea);
         URL imageURL = null;
         try {

         imageURL = new URL(mainDirectory+"quindell.png");
         } catch (MalformedURLException me) {
         me.printStackTrace();
         }

         //--- Load the image and wait for it to load
         Image image = Toolkit.getDefaultToolkit().getImage(imageURL);
         mt.addImage(image, 0);
         */

        while (lineCount != 0) {
            try {

                lineStart = textarea.getLineStartOffset(lineNumber);
                lineEnd = textarea.getLineEndOffset(lineNumber);
                strText = textarea.getText(lineStart, lineEnd - lineStart);
            } catch (Exception exception) {
                System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
            }

            g2d.drawString(strText, 1, (lineNumber + 1) * 18);
            //spacing    between lines
            lineNumber = lineNumber + 1;
            lineCount--;
        }
        return Printable.PAGE_EXISTS;
    }
}
于 2014-01-09T22:08:31.040 回答
0

我完成了这个编程,它对我来说很好。你可能会从中得到一些帮助。检查一下。

public class Receipt
{

PageFormat format = new PageFormat();
Paper paper = new Paper();

double paperWidth = 3;//3.25
double paperHeight = 500.69;//11.69
double leftMargin = 0.12;
double rightMargin = 0.10;
double topMargin = 0;
double bottomMargin = 0.01;

paper.setSize(paperWidth * 200, paperHeight * 200);
paper.setImageableArea(leftMargin * 200, topMargin * 200,
     (paperWidth - leftMargin - rightMargin) * 200,
     (paperHeight - topMargin - bottomMargin) * 200);

format.setPaper(paper);

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
//testing 

PrinterJob printerJob = PrinterJob.getPrinterJob();
Printable printable = new ReceiptPrint();

format = printerJob.validatePage(format);
printerJob.setPrintable(printable, format);
try {
   printerJob.print(aset);
}
catch (Exception e) {
    e.printStackTrace();
}
class ReceiptPrint implements Printable {
SimpleDateFormat df = new SimpleDateFormat();
String  receiptDetailLine ;
public static final String pspace="               ";//15-spaces

public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)  
throws PrinterException 
{

df.applyPattern("dd/MM/yyyy HH:mm:ss");
String strText =null; 
final String LF = "\n";// text string to output
int lineStart;           // start index of line in textarea
int lineEnd;             // end index of line in textarea
int lineNumber;   
int lineCount;
final String SPACE = "          ";//10 spaces
final String SPACES = "         ";//9
final String uline ="________________________________________";
final String dline ="----------------------------------------";
String greetings ="THANKS FOR YOUR VISIT";
receiptDetailLine= Integer.toString(SystemConfig.currentLocationCode) + "-"
+ Integer.toString(SystemConfig.tillNumber) + "-" + 
Integer.toString(EPOSFrame.mainFrame.currentUser.data.userID) + "-" + 
Receipt.order.name;

   Graphics2D g2d = (Graphics2D) graphics;
Font font = new Font("MONOSPACED",Font.BOLD, 9);

if (pageIndex < 0 || pageIndex >= 1) {
      return Printable.NO_SUCH_PAGE;
  }
 JTextArea textarea = new JTextArea(10,40);

 //testing
 if(SystemConfig.receiptAddressLine1!="")
 {
 textarea.append(SPACES+SystemConfig.receiptAddressLine1 +"\n");
 }
 if(SystemConfig.receiptAddressLine2!="")
 {
 textarea.append(" "+SPACES+SystemConfig.receiptAddressLine2 +"\n");
 }
 if(SystemConfig.receiptAddressLine3!="")
 {
 textarea.append(SPACES+SystemConfig.receiptAddressLine3 +"\n");
 }
 if(SystemConfig.receiptAddressLine5!="")
 {
 textarea.append(""+SPACES+SystemConfig.receiptAddressLine5 +"\n");
 }
 if(SystemConfig.receiptAddressLine4!="")
 {
 textarea.append(SPACES+SystemConfig.receiptAddressLine4 +"\n");
 }
 textarea.append(uline+"\n");
 textarea.append("Order Ref:" +"   "+receiptDetailLine+"\n");
 textarea.append(dline+"\n");
 textarea.append(" Qty     Description"+SPACES+"  Price"+LF);
 textarea.append(dline+"\n");

System.out.println(2);
TransactionItemPayment payment = null;
Enumeration transEnumeration = Receipt.order.m_transactions.elements();
int qty= 0;
String desc= "";
while (transEnumeration.hasMoreElements())
{

  TransactionItem ti = (TransactionItem) transEnumeration.nextElement();
  StringBuffer  price = new StringBuffer(String.valueOf(ti.getValue()));
  String  printLine = ti.getReceiptLine();

  if (printLine!=null)
  {
    qty=ti.getQuantity();
    desc = ti.getTopDisplayLine();


    if (price.length()>=2)
    {
      price.insert(price.length() - 2, '.');
    }


    textarea.append( printLine+LF );
    qty=0;
    desc="";

  }
  else if (ti instanceof TransactionItemPayment)
  {
    payment = (TransactionItemPayment) ti;
  }
  }
 long  serviceCharge = Receipt.order.calcServiceCharge();
 if (serviceCharge>0)
 {
  double  charge = (double) serviceCharge / 100;
  String  valueString = 
  SystemConfig.decimalFormat.format(charge).replace((char)163,' ');
  String printedLine = "       Service Charge    " +SPACE+ valueString;
  textarea.append( printedLine + LF);
}
else if (SystemConfig.serviceCharge)
{
  String printedLine = "       Service Charge Complimentary";
  textarea.append( printedLine + LF);
}
long  autoDiscount = Receipt.order.calcAutoDiscount();
if (autoDiscount>0)
{
  double  discount = (double) autoDiscount / 100;
  String  valueString =  
  SystemConfig.decimalFormat.format(discount).replace((char)163,' ');
  String printedLine = "       Discount:"+pspace+valueString;
  textarea.append( printedLine + LF);
}

long total = (long)Receipt.order.getOrderTotal() +  

  Receipt.order.calcServiceCharge() - Receipt.order.calcAutoDiscount();
  String formattedTotal = SystemConfig.decimalFormat.format((double)total /
  100D);

textarea.append(LF+"       SubTotal:"+pspace+formattedTotal+LF);
textarea.append("            Gratuity:______________________"+LF);//12 space
textarea.append("              Total:_______________________"+LF);
textarea.append("            Signature:_____________________"+LF);

textarea.append(LF+SPACES+"   Your Reciept\n"+ SPACE+greetings+LF);
textarea.append(df.format(new Date()) + LF);
textarea.setEditable(false);

  g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());


  g2d.setFont(font);
  lineNumber = 0;
  lineCount = textarea.getLineCount();
   strText = textarea.getText();
   /*MediaTracker mt = new MediaTracker(textarea);
   URL imageURL = null;
   try {

     imageURL = new URL(mainDirectory+"quindell.png");
   } catch (MalformedURLException me) {
     me.printStackTrace();
   }

 //--- Load the image and wait for it to load
   Image image = Toolkit.getDefaultToolkit().getImage(imageURL);
   mt.addImage(image, 0);
   */

  while (lineCount!=0){
  try {

        lineStart = textarea.getLineStartOffset(lineNumber);
        lineEnd = textarea.getLineEndOffset(lineNumber);
        strText = textarea.getText(lineStart, lineEnd-lineStart);
        } catch( Exception exception) 
        {
            System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
        }

                   g2d.drawString(strText,1,(lineNumber + 1) *18);
                   //spacing    between lines
                    lineNumber = lineNumber + 1;
                     lineCount--;
         }
         return Printable.PAGE_EXISTS;
     }
    } 
于 2013-03-13T17:02:32.320 回答