package com.zbf.system.print;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.*;

/**
 * 源辰信息
 * 打印对象 -> 实现Printable接口即可调用打印机打印
 * @author navy
 * 2017年5月23日
 */
public class YcPrinter {
    private static final Logger logger = LoggerFactory.getLogger(YcPrinter.class);
	private SalesTicket salesTicket;
	private String printerName;
	
	public YcPrinter(SalesTicket salesTicket){
		this.salesTicket=salesTicket;
		this.printerName = salesTicket.getPrintName();
	}
	
    public void printer() {  
        try {  
            //Book 类提供文档的表示形式，该文档的页面可以使用不同的页面格式和页面 painter
            Book book = new Book(); //要打印的文档
            
            //PageFormat类描述要打印的页面大小和方向  
            PageFormat pf = new PageFormat();  //初始化一个页面打印对象
            pf.setOrientation(PageFormat.PORTRAIT); //设置页面打印方向，从上往下，从左往右
          
            //设置打印纸页面信息。通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。  
            Paper paper = new Paper(); 
            paper.setSize(30000,300);// 纸张大小
            paper.setImageableArea(1,0.5,30000,300);// A4(595 X 842)设置打印区域，其实0，0应该是72，72，因为A4纸的默认X,Y边距是72
            pf.setPaper(paper);  
  
            book.append(salesTicket,pf);
           
            PrinterJob job = PrinterJob.getPrinterJob();   //获取打印服务对象  
            if (StringUtils.isNotBlank(printerName)) {// 不指定的话会调用默认的打印机
                PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);

                logger.info("input printer name:{}" ,printerName);

                for (int i = 0; i < printServices.length; i++) {
                    String svcName = printServices[i].toString();

//				logger.debug("print service:" + svcName);

                    if (svcName.endsWith(printerName)) {

					logger.debug("found printer:" + svcName);

                        try {
                            job.setPrintService(printServices[i]);
                        } catch (PrinterException e) {
                            logger.error("can not set print service:" + svcName);
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
            job.setPageable(book);  //设置打印类  
  
            job.print(); //开始打印 
        } catch (PrinterException e) {  
            e.printStackTrace();  
        }  
    }  
}